Since there is no way to prevent an iframe from redirecting the top frame besides sandboxing which prevents other features required for viewability tracking I would like to track redirects. Since one site can have more than one iframe, it could be any of these.
Is there any way to track/find out which one (specific iframe) caused the top frame redirect?
Here is a sandbox (use browser console and enable preserve log):
3 Answers
Answers 1
If you have control over all your frames you can implement interaction between frames with postMessage. Flow:
- Frame want to execute redirect - it sends a message to parent frame with redirect request.
- Parent frame executing redirect and know which frame caused a redirect.
Parent:
window.addEventListener("message", (event) => { // show message source (your frame) console.log(event.source); const message = event.data; console.log(`Frame ID: ${message.frameId}`); if(message.messageType === "redirect") { window.location.href = message.redirectUrl; } });
Child frame:
function redirect(url) { var message = { messageType: "redirect", frameId: "frame1" redirectUrl: url } window.parent.postMessage(message, "*"); }
Answers 2
Apart from postMessage approach, you can show a dialog box before redirecting to another domain/application and then the user can decide - to stay or leave the current application. You can also track the current target (i.e. iframe in your case).
window.onbeforeunload = function (e) { console.log(e.currentTarget.location.href); return 'Stop redirection. Show dialog box.'; };
Answers 3
you can add an id
to the iFrame
and get it under e.currentTarget.iframe.id
, in your case you'll get the last iFrame
id that caused the redirection :
window.onbeforeunload = function(e) { console.log(e.currentTarget.iframe.id); }; var iframe = document.createElement('iframe'); iframe.src = 'iframe2.html'; iframe.id = 'iframe2'; document.body.appendChild(iframe); var iframe = document.createElement('iframe'); iframe.src = 'iframe.html'; iframe.id = 'iframe1'; document.body.appendChild(iframe);
0 comments:
Post a Comment