3

Hello guys I have some problem with my website. Here's the situation:

Page 1

<script type="text/javascript" src="jscript.js">
<input type="button" value="change" onClick="changeAttr()">

Page 2

<script type="text/javascript" src="jscript.js">
<input type="text" value="Hello" id="dynamictext">

jscript.js

function changeAttr(){
document.getElemenyById('dynamictext').value="World";
}

Now these 2 pages are open on different tabs. What I want to happen is whenever the button on page 1 is clicked, the value of input text on page 2 will change to "World". How can I make this possible with Javascript or Jquery?

clyde
  • 61
  • 2
  • 9

4 Answers4

6

The 1st tab has the task to change a value in localStorage. localStorage.setItem('superValue', 'world');

Meanwhile the 2nd tab would be "listen" to changes on that localStorage value:

var dinamictext = document.querySelector('dinamictext');

setInterval(function () {
    if (dinamictext.value !== localStorage['superValue']) {
        dinamictext.value = localStorage['superValue'];
    }
}, 100);

This of course works only with pages on the same domain.

Andrés Torres
  • 747
  • 5
  • 16
0

You cannot directly access DOM elements from one tab to another. That would be a serious security issue.

  • You can communicate between your two pages (assuming they are both under your control) using cookies. See this other SO question on the subject.
  • You can also use LocalStorage API, assuming you are targeting only modern browsers. See this SO answer.

Both methods will allow you to share data. Then, you will have to define your own protocol, in order to manipulate DOM according to the received command.

Community
  • 1
  • 1
Guillaume Poussel
  • 9,572
  • 2
  • 33
  • 42
  • 1
    `w = window.open('/same-domain', '_blank'); w.window.document.body.innerHTML = 'this totally works'` It's not a security issue when it meets the same-origin policy and is opened from code. – zzzzBov Oct 07 '13 at 18:21
  • That suppose the first tab opens the second. That is not mentionned by the OP. – Guillaume Poussel Oct 08 '13 at 06:07
  • 1
    I was replying to your statement that "You cannot directly access DOM elements from one tab to another." The point is that you were making an incorrect generalization. – zzzzBov Oct 08 '13 at 12:40
0

You can use HTML5 Storage. Here is a simple example

emotionull
  • 595
  • 2
  • 8
  • 24
0

The other answers are perfect if both pages belong to the same site. If they're not on the same site however, you'd need a server solution. One page would send a request to the server, and the other page would also have to call the server looking for instructions, and execute those instructions when received. In that scenario, if they're on separate sites, AJAX probably wouldn't work, and you'd have to resort to something like JSONP.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136