Skip to content

Instantly share code, notes, and snippets.

@mladenp
Created October 8, 2018 16:53
Show Gist options
  • Save mladenp/55886a2ce92b05b1b52aeb24b7341119 to your computer and use it in GitHub Desktop.
Save mladenp/55886a2ce92b05b1b52aeb24b7341119 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