通過單擊第一個選項卡中的鏈接打開新選項卡時,是否可以刷新當前打開的選項卡? 基本上,最終的結果會是這樣的:第一個標籤是打開的,第一個標籤中打開的頁面上的鏈接被點擊(用鼠標中鍵或類似的東西,只是爲了讓它在第二個在第二個選項卡中打開被點擊的鏈接,然後第一個選項卡自動刷新。我希望我可以理解地解釋它。注意:我沒有設計自己的網站,我正在尋找一個Greasemonkey的網站插件。當打開新選項卡時,使用Javascript刷新當前打開的選項卡
1
A
回答
1
讓我們假設你有你的頁面上點擊此鏈接:
<a href="http://server.com/url-to-second-tab" target="_new">Link which opens new tab and refreshes current one</a>
在js腳本添加這個(假設你使用jQuery,你說):
$(document).ready(function(){
$('body').on('click','a',function(e){
e.preventDefault()
// Open new tab - in old browsers, it opens a popup window
window.open($(this).attr('href'), '_blank');
// reload current page
location.reload();
})
})
請測試它在所有瀏覽器,因爲在某些瀏覽器中,它可能會將鏈接作爲彈出窗口而不是新標籤打開。
作爲一個快速測試,與Chrome的F12開發工具開放,譜寫控制檯:
window.open('https://google.com', '_blank');location.reload();
0
是的,它是與document.body方法。
聲明你的窗口:
w = window.open("yourUrl", "MYtest", "width=700, height=500");
而在你的功能,您可以用document.body的方法來訪問:
html = "I Append my new html";
$(w.document.body).html(html);
+0
,我想我沒有解釋的不夠好。這應該更好地顯示我的意思:http://i.imgur.com/6BPPVOY.png –
+0
好吧抱歉,如果難以理解你想要什麼。請添加更多細節。也許是最好的圖片。 –
0
你需要的東西是這樣的(內部jQuery代碼):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<a id="myLink" href="http://www.google.com">Click me</a>
<div id="toUpdate">Not updated</div>
</body>
<script>
$(function() {
$("#myLink").on("click", function(event) {
event.preventDefault();
window.open(event.target.href, '_blank');
$("#toUpdate").text("Go on google");
}).on("mousedown", function(event) {
event.preventDefault();
if (event.which === 2)
$("#toUpdate").text("Go on google");
});
});
</script>
</html>
編輯添加Firefox支持
似乎是唯一一個工作,非常感謝:) –