Skip to content

Instantly share code, notes, and snippets.

@yanky2000
Forked from hdodov/iframechange.js
Created September 18, 2020 12:36
Show Gist options
  • Save yanky2000/c576a5811f701f8a3a15c7e41029d58b to your computer and use it in GitHub Desktop.
Save yanky2000/c576a5811f701f8a3a15c7e41029d58b 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