Link between browser tab

I have an html page (main.html) that opens a new tab in the same domain using javascript using the window.open method ("newtab.html").

In a new tab, users do something, ending its action by pressing a button. At this point, I would like to send a message to the window that opens. I tried with postMessage, but from a new tab I cannot have a link to the opener.

From the new tab, I would like something like, but I have "ko"

var w = window.opener; if (w) { w.postMessage("hi", "http://10.150.10.43"); } else { alert("ko"); } 

What is the best way to send a message from a secondary tab / window to the primary (in the same domain)?

Thank you very much luke

+6
source share
1 answer

This is strange. Opening a new window with window.open("newtab.html") should allow the newly opened window to refer to the opener through window.opener .

In any case, there are several other options for communication between two windows in the same domain. I think the following two are the easiest to implement:

  • Use localStorage . If you save some data under a certain key in localStorage in a new tab window, a storage event will appear in the window that opens. If you catch an event with a handler, you can read the data from localStorage that you wrote in a new tab window. Please note that events are triggered only if both pages are in the same domain, and if there are actually two windows (events do not fire in the same window where the data is recorded). For more information on how to do this, see, for example: http://diveintohtml5.info/storage.html

  • Use shared web workers . A web worker is a JS script that runs in the background in a separate thread. Shared web workers are a special type of web worker that allows any number of parent documents to communicate with one worker. Thus, you can use the worker to send messages between the opening window and the new tab window. The API for communicating with workers is very similar to the PostMessage API. For more information on how to do this, see, for example: http://www.sitepoint.com/javascript-shared-web-workers-html5/ .

+12
source

Source: https://habr.com/ru/post/923652/


All Articles