如果第二个标签

时间:2015-06-26 06:32:16

标签: javascript greasemonkey userscripts

我在Firefox中打开了2个标签。我需要以下内容。

如果在第二个标签内容中找到以下单词,则用户脚本将关闭第二个标签,然后重新加载第一个标签。

抱歉,此页面无法使用。

我已经尝试但是它正在关闭第二个标签但没有重新加载第一个标签。



// ==UserScript==
// @name        Ins Sorry
// @namespace   Ins Sorry
// @version     1
// @include         https://instagram.com/*
// @match      https://instagram.com/*
// ==/UserScript==
if (
  (
    document.documentElement.textContent || document.documentElement.innerText
  ).indexOf('Sorry') > -1
) {

location.reload();
window.top.close();
}




1 个答案:

答案 0 :(得分:0)

用户脚本无法全局访问您的Internet浏览器,它只知道调用它的页面,并且完全不了解其他选项卡。它的操作仅限于页面的上下文和它执行的选项卡。

这就是为什么你不能要求你的脚本更新第一个标签并关闭第二个标签。

使用您的代码会发生什么:

location.reload(); // Try to reload the current tab (the 2nd one)
window.top.close(); // Close the current tab (the 2nd one)

但是,usesrcript可以访问名为Web Storage的浏览器的共享内存空间。您可以使用在第二个选项卡上运行的脚本在此空间中编写内容,并且第一个选项卡的脚本可以读取此内容。

有用的是在更改此内存空间时触发的there is an event

请参阅此相关答案:Javascript; communication between tabs/windows with same origin

因此,您可以在脚本上为此事件附加处理程序,该处理程序在第一个选项卡中运行,并在更改值时关闭选项卡。

第二个标签用户:

if ((document.documentElement.textContent || document.documentElement.innerText).indexOf('Sorry') > -1) {
    sessionStorage.setItem("word_found", Date.now());
    window.top.close();
}

第一个标签用户:

window.addEventListener("storage", function(event) {
   if (event.key == "word_found") {
       location.reload();
   }
});