I am looking to pass information from a parent window to a child window, but cannot use a query string because there is too much information and the pop-up gets blocked. They have different domains. (cross-origin) How would I achieve this? I want the information to be passed as soon as the child window is open (the JavaScript is loaded)
Asked
Active
Viewed 527 times
-2
-
Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output. – mplungjan Oct 10 '18 at 07:29
-
Same origin, or cross-domain? What has your research turned up so far, what have you tried? – misorude Oct 10 '18 at 07:29
-
If same domain you can just access opener.someValue. If the opener is not available and it is on the same origin, try localStorage or sessionStorage – mplungjan Oct 10 '18 at 07:30
-
@misorude cross-origin. I have tried a query-string. I understand you can use an event listener, and post a message to the child window, although, the child has to be loaded (the JS has to be loaded) to receive the message through the event listener (my understanding of it). – Ryan Oct 10 '18 at 07:32
-
@mplungjan is it possible to use localStorage or sessionStorage with cross-origin? – Ryan Oct 10 '18 at 07:33
-
Are you in control of both sides, or do you have to make do with what the document loaded into the popup already offers? _“although, the child has to be loaded (the JS has to be loaded) to receive the message”_ - the child could as well post a message to the opening window first, “I’m ready, come at me (with the data) bro” … – misorude Oct 10 '18 at 07:37
-
Can you do something like `w.addEventListener("load",()=>{w.postMessage(...)})` so that you post message after it is loaded? – Ricky Mo Oct 10 '18 at 07:37
-
@misorude I have control of both side, but they do not have the same domain. So are you suggesting the child could post a message to the parent to say 'I am loaded' and then the parent could post a message back with the information? – Ryan Oct 10 '18 at 07:40
-
@RickyMo would this be waiting for the child to load or the parent to load? – Ryan Oct 10 '18 at 07:40
-
1Yes, that’s what I meant. Another alternative, if you can use server-side coding on the child popup side, could be to just open the popup and then submit a hidden form to it, so that you can POST a larger amount of data than GET would allow for. – misorude Oct 10 '18 at 07:43
1 Answers
3
Posting an "I am ready" message should work.
Parent:
var child = window.open(childURL);
window.addEventListener("message",(e)=>{
if(e.data == "ready")
{
e.source.postMessage("some data for you","*");
}
})
Child:
window.addEventListener("load",()=>{
window.opener.postMessage("ready","*");
})
window.addEventListener("message",(e)=>{
console.log(e.data);
});
Ricky Mo
- 5,242
- 1
- 12
- 25