-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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