Skip to content

Instantly share code, notes, and snippets.

@hvvvva
Forked from mladenp/iframe-listener.js
Created December 5, 2022 14:43
Show Gist options
  • Save hvvvva/54a3028685136c2d61d2b4a2cb051cf3 to your computer and use it in GitHub Desktop.
Save hvvvva/54a3028685136c2d61d2b4a2cb051cf3 to your computer and use it in GitHub Desktop.
iframe URL redirect listener
function iframeURLChange(iframe, callback) {
var unloadHandler = function () {
// Timeout needed because the URL changes immediately after
// the `unload` event is dispatched.
setTimeout(function () {
callback(iframe.contentWindow.location.href);
}, 0);
};
function attachUnload() {
// Remove the unloadHandler in case it was already attached.
// Otherwise, the change will be dispatched twice.
iframe.contentWindow.removeEventListener("unload", unloadHandler);
iframe.contentWindow.addEventListener("unload", unloadHandler);
}
iframe.addEventListener("load", attachUnload);
attachUnload();
}
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