Skip to content

Instantly share code, notes, and snippets.

@hdodov
Last active September 23, 2024 14:17
Show Gist options
  • Save hdodov/a87c097216718655ead6cf2969b0dcfa to your computer and use it in GitHub Desktop.
Save hdodov/a87c097216718655ead6cf2969b0dcfa 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);
});
@nicojs
Copy link

nicojs commented Oct 15, 2018

Is it possible to detect url changes with pushState?

@santis14
Copy link

Uncaught TypeError: Cannot read property 'addEventListener' of null

@allthesignals
Copy link

@santis14 you're probably trying to use this on a cross-origin iFrame.

@ibnsultan
Copy link

am having the same issue here as @santis14 and the domain + iframe content both belong on the same domain

@cmddavid
Copy link

cmddavid commented May 8, 2023

@ibnsultan did you also validate you are using the same subdomain, port and protocol? Since those are also part of the origin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment