Need userscript to close the 2nd tab and reload the 1st tab if a word fround in 2nd tab

564 views Asked by At

I have 2 tab opened in firefox. I need the following thing.

If the following word is found in the 2nd tab content, then the userscript will close the 2nd tab and then reload the 1st tab.

Sorry, this page isn't available.

I have tried but it is closing the 2nd tab but not reloading the 1st tab.

// ==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

There are 1 answers

6
Delgan On

An userscript does not have global access to your internet browser, it knows only the page on which it was called and knows absolutely nothing about the other tabs. Its action is limited to the context of the page and the tab on which it executes.

This is why you can not ask your script to update the first tab and close the second.

What happens using your code:

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

However, usesrcript have access to a shared memory space of your browser called Web Storage. You can write content in this space with a script that runs on the second tab, and the script of the first tab can read this content.

What is useful is that there is an event that triggers when this memory space is changed.

See this related answer: Javascript; communication between tabs/windows with same origin

So you can attach a handler to this event on your script which runs in the first tab, and close the tab when a value is changed.

2nd tab userscript:

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

1st tab userscript:

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