Home > OS >  Check whether an URL is already open or not in Background script
Check whether an URL is already open or not in Background script

Time:07-29

I send message using chrome.runtime.sendMessage({}); from my content.js and it is received by background script which opens a HTML file:

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    chrome.tabs.create({url: 'popup.html'});
});

If the popup.html is already open, I don't want to open it again, so there should be a ifcondition to check whether it is already open.

But what do I put in side the if condition before chrome.tabs.create({url: 'popup.html'}); in the background script?

Please note that I am looking the solution inside banckground script.

Please provide the solution according to the scripts given in this answer.

CodePudding user response:

You need to check every tab if you extension popup page opened

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    var flag = false;
    chrome.tabs.query({}, function (tabs) {
        for (let index = 0; index < tabs.length; index  ) {
            const tab = tabs[index];
            if (tab.url.includes("chrome-extension://")) { //You can filter by extension id or popup.html if you want
                flag = true;
            }
        }
        if(flag){
            chrome.tabs.create({ url: 'err.html' });
        }
        else{
            chrome.tabs.create({ url: 'popup.html' });
        }
    });
});

You can filter by extension id or popup.html if you want in if (tab.url.includes("chrome-extension://")) {. For better results you can filter by your extension id

err.html

<html>
    <script src="err.js"></script>
</html>

err.js

alert("Popup already opened");
window.close();

if popup tab already opened then open err.html and show alert then close. But you can't alert in background.js because background.js does not have a page to show alert.

CodePudding user response:

var tab, PAGE_URL = "https://www.google.com", btn = document.getElementById('btn');

  btn.addEventListener('click', function() {
    if (!tab || tab.closed) {
      tab = window.open(PAGE_URL, "_blank");
    } else {
      alert('window is already opened');
    }
  });
<span id="btn">Open Tab</span>

I think it might work for your

  • Related