Skip to content

Instantly share code, notes, and snippets.

@kevgathuku
Forked from hdodov/iframechange.js
Created October 3, 2019 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevgathuku/1e5f34b8344198d687f394ee25e7700e to your computer and use it in GitHub Desktop.
Save kevgathuku/1e5f34b8344198d687f394ee25e7700e to your computer and use it in GitHub Desktop.
HTML iframe URL change listener for tracking when a new iframe page starts to load
function iframeURLChange(iframe, callback) {
var lastDispatched = null;
var dispatchChange = function () {
var newHref = iframe.contentWindow.location.href;
if (newHref !== lastDispatched) {
callback(newHref);
lastDispatched = newHref;
}
};
var unloadHandler = function () {
// Timeout needed because the URL changes immediately after
// the `unload` event is dispatched.
setTimeout(dispatchChange, 0);
};
function attachUnload() {
// Remove the unloadHandler in case it was already attached.
// Otherwise, there will be two handlers, which is unnecessary.
iframe.contentWindow.removeEventListener("unload", unloadHandler);
iframe.contentWindow.addEventListener("unload", unloadHandler);
}
iframe.addEventListener("load", function () {
attachUnload();
// Just in case the change wasn't dispatched during the unload event...
dispatchChange();
});
attachUnload();
}
// Usage:
iframeURLChange(document.getElementById("mainframe"), function (newURL) {
console.log("URL changed:", newURL);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment