Javascript event dispached in a popup window that has been redirected
Asked Answered
E

1

6

I have a page A that opens a popup to B. Page B, after some jobs, always redirects to another page C in the pop up. Page C then dispatches an event to send some data to page A, but page A has no reference to page C to register the event handler. The code I tried is somewhat like this:

PageA:

function handler(e) {
    alert(e.detail.message);
}
var popup = window.open('/PageB.aspx');
popup.addEventListener("dispatch", handler, false);

PageB:

location.href = "PageC.aspx";

PageC:

var event = new CustomEvent(
        "dispatch",
        {
            detail: {
                message: "Test"
            },
            bubbles: true,
            cancelable: true
        }
    );

window.dispatchEvent(event);

But this is not working, because when I redirect, PageA misses the reference to PageC. Does anyone knows a way to fix this?

Erde answered 19/12, 2012 at 14:27 Comment(1)
Is Page C in the same domain as Page A? If not, you need to use postMessage instead.Madaras
M
1

If Page C is in the same domain as page A, try

window.opener.dispatchEvent(event);

If not, you need to use postMessage instead, which means you have to serialize your event to a string and listen for messages on Page A.

Madaras answered 19/12, 2012 at 14:49 Comment(3)
Page C is in the same domain, but in the stuff done by Page B there is also a redirect to another domain that turn to Page C, so the reference to opener is lost. I think that I must use postMessage, but Page A still not have a refecerence to Page C so, can you show me how to do this?Erde
postMessage won't work unless you have a reference to the parent window. Try window.parent instead.Madaras
This related question might help.Madaras

© 2022 - 2024 — McMap. All rights reserved.