Javascript, track iframes redirecting top window

前端 未结 4 1471
谎友^
谎友^ 2021-02-12 23:38

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 trac

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 00:19

    If you have control over all your frames you can implement interaction between frames with postMessage. Flow:

    1. Frame want to execute redirect - it sends a message to parent frame with redirect request.
    2. 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, "*");
    }
    

提交回复
热议问题