Last active
September 23, 2024 14:17
-
-
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
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); | |
}); |
@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
am having the same issue here as @santis14 and the domain + iframe content both belong on the same domain