clyde
clyde

Reputation: 61

Change element attribute of another page

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?

Upvotes: 3

Views: 5961

Answers (4)

Joe Enos
Joe Enos

Reputation: 40413

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.

Upvotes: 0

emotionull
emotionull

Reputation: 615

You can use HTML5 Storage. Here is a simple example

Upvotes: 0

Andr&#233;s Torres
Andr&#233;s Torres

Reputation: 733

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.

Upvotes: 6

Guillaume Poussel
Guillaume Poussel

Reputation: 9822

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.

Upvotes: 0

Related Questions