一種方法是不喜歡其他的答案是什麼精神疾病讓每個選項卡與中央服務器通信,中央服務器將獲取/發送數據以保持使用AJAX更新兩個選項卡。
但是我在這裏告訴你另一種方式,它是使用我們已經爲這種任務設計的。什麼所謂的瀏覽器localStorage
瀏覽器存儲工作原理是這樣的僞代碼:
//set the value, it works as a hash map or assoc array.
localStorage .setItem("some_index_key", "some data") ;
// get the value by it's index key.
localStorage .getItem("some_index_key") ; // will get you "some data"
,所有的數據都將打開的選項卡爲同一域之間共享。您可以添加事件偵聽器,以便每當一個值發生更改時,它都會反映在所有選項卡上。
addEvent(window, 'storage', function (event) {
if (event.key == 'some_index_key') {
output.innerHTML = event.newValue;
}
});
addEvent(myInputField, 'keyup', function() {
localStorage.setItem('some_index_key', this.value);
});
看看這個DEMO,您可以編輯頁面上-A一個字段,該值將在頁面-B下線,而不需要負擔的網絡中得到體現。
要了解更多,read this。
真實的例子。背景顏色由另一個選項卡控制。
var screenone = document.getElementById('screenone');
screenone.addEventListener('keydown', screenOneFunction);
screenone.addEventListener('change', screenOneFunction);
function screenOneFunction()
{
document.body.style.backgroundColor = this.value;
localStorage.setItem("color1", this.value);
}
var screentwo = document.getElementById('screentwo');
screentwo.addEventListener('keydown', function (evt) {
localStorage.setItem("color2", this.value);
});
screentwo.addEventListener('change', function (evt) {
localStorage.setItem("color2", this.value);
});
var thebutton = document.getElementById('thebutton');
thebutton.addEventListener('click', function (evt) {
localStorage.clear();
screenone.value = "";
screentwo.value = "";
document.body.style.backgroundColor = "";
});
var storageHandler = function() {
document.body.style.backgroundColor = localStorage.color2;
var color1 = localStorage.color1;
var color2 = localStorage.color2;
screenone.value = color2;
screentwo.value = color1;
};
window.addEventListener("storage", storageHandler, false);
.screenone{ border: 1px solid black;}
input{ margin: 10px; width: 250px; height: 20px; border:round}
label{margin: 15px;}
<html>
<head>
</head>
<body>
<label> Type a color name e.g. red. Or enter a color hex code e.g. #001122 </label>
<br>
<input type="text" class="screenone" id="screenone" />
<label> This tab </label>
<br>
<input type="text" class="screentwo" id="screentwo" />
<label> Other opned tabs </label>
<br>
<input type="button" class=" " id="thebutton" value="clear" />
</body>
</html>
最簡單的方法是使用PHP並通過GET或POST來更改內容,我相信。 –
頁面是否同時打開?然後,只有其中一個頁面已被其他頁面打開,才能完成此操作。 – flec
可能重複的[瀏覽器標籤頁/窗口之間的JavaScript通信](http://stackoverflow.com/questions/4079280/javascript-communication-between-browser-tabs-windows) –