Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate between tabs dom without window ref [duplicate]

I use the following to open new tab (in new process) with some page content,

var p = document.getElementById("myElement"); 
var a = document.createElement('a');
a.setAttribute('href',".../mypage.html");
a.setAttribute('rel',"noreferrer");
a.setAttribute('target',"_blank");
p.appendChild(a);
a.click();

http://news.softpedia.com/news/Force-Google-Chrome-to-Open-Links-in-New-Processes-128962.shtml

This is working and the new tab is open with myPage.html content.

Assume that this is myPage(just for sample...) how should I access it?

<!DOCTYPE html>
<html>
<body>

<h1> Heading</h1>
<p> paragraph.</p>
 <button type="button">Click Me!</button>

</body>
</html>

Now Let's go to the tricky/advanced :) part...

when you use window.open (which I cannot use )this is quite simple since you can use various techniques .

 1. using window object
 2. post message
 https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
 3. cookies 
 4. localStorage

But here I open this new page without the reference which is got with window.open

My question is:

How can I access to this new tab dom if I want to change something

like image 583
John Jerrby Avatar asked Oct 18 '16 20:10

John Jerrby


1 Answers

Parent page JavaScript:

var lastMessage;
setInterval(function() {
  var message = localStorage.getItem('message-to-parent');
  if (message && message !== lastMessage) {
    lastMessage = message;
    // your code here
    alert('There is a new message for you: ' + message);
  }
}, 100);

Child page JavaScript:

localStorage.setItem('message-to-parent', 'hello, my parent!');

If you have a lot of animations and other huge JS code, I'd suggest to increase the timer interval, or better to solve the issue with window.

like image 92
fremail Avatar answered Sep 19 '22 09:09

fremail