react
react copied to clipboard
Iframe load event not firing in Chrome and Safari when src is 'about:blank'
See: https://jsfiddle.net/pnct6b7r/
It will not trigger the alert in Chrome and Safari, but it will work in Firefox and even IE8.
Is this a React issue or Webkit issue? If it is a Webkit issue, should we "fix it" in React given that we want consistent events across browsers?
ps: The JSFiddle was based on the isuse #5332.
Unlike in #5332, this does appear to fire in chrome (http://jsfiddle.net/x14c21g0/) so it's odd that we're not firing the event in React.
+1
+1
+1
Please don‘t +1. If you’d like to see this fixed, please help figure out why this happens and/or contribute a fix.
I am experiencing this issue as well with embed tags when trying to listen to whether or not a PDF has loaded, or has at least started loading.
So the reason that we don't dispatch is because the load event is being dispatched by the browser synchronously when the iframe is appended to it's parent. Since this happens during the commit phase the event is ignored since we disable the synthetic event system while committing.
There's some context on this in https://github.com/whatwg/html/issues/490. There's ambiguity in the spec around load events for iframes and about:blank, which is why we don't see this behavior in every browser.
Outside of waiting for WATWG and browser vendors to resolve this ambiguity, resolving this would probably involve implementing a event queue that enqueues a subset of events during the commit phase and dispatches them afterwards.
This is how I fixed this very issue :
- Create the
iframewith theonLoadevent handler and a ref, leavingsrcblank, e.g.<iframe ref={ frameRef } onLoad={ handleLoad } /> - Inside a
useEffectfunction, set thesrcproperty, e.g.frameRef.current.src = ....
As @aweary explained, the iframe's load event is fired before React can attach the listener to it. I got a hint of this when the load event would fire on hot reload, but not when refreshing the page. This is a browser quirk, but React could perhaps fix this if event handler would be attached before the element got inserted to the DOM? I haven't really looked into React's source code (never had to) so I'm merely positing a reason.
Expanding on the suggestion from @yanickrochon...
Let me introduce you to react-onload-iframe:
iframe wrapper component that enables onLoad event handling in all browsers.
NPM: https://www.npmjs.com/package/react-onload-iframe
Github: https://github.com/TheJanitor337/react-onload-iframe
Example: https://react-ts-av8uan.stackblitz.io
P.S. I'll get a good laugh if anyone uses the npm package. Feel free to copy/paste from the repo. It's WTFPL.