Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an extension close a tab?

This is in continuation of: Script to close the current tab in Chrome

I'm trying now do it in an extension instead of a tampermonkey script, I have "matches" : ["*://*.youtube.com/*", "*://youtube.com/*"], in my manifest file, and the js script is simply chrome.tabs.remove(tab.id); or window.close(); but both don't close a youtube.com page that I open.

Could it be that it's also impossible to close a tab with an extension?

like image 549
shinzou Avatar asked Jan 29 '26 12:01

shinzou


1 Answers

chrome.tabs is not available to content scripts, so if that's in your code, it fails with an exception.

window.close has a caveat:

This method is only allowed to be called for windows that were opened by a script using the window.open() method. If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script.

I'm not sure if it applies to content scripts - but suppose it does.

You can make it work by adding a background script (that has access to chrome.tabs) and either detect navigation from there, or just message the background script from a context script to do it.

  1. Messaging the background:

    // Content script
    chrome.runtime.sendMessage({closeThis: true});
    
    // Background script
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
      if(message.closeThis) chrome.tabs.remove(sender.tab.id);
    });
    

    I would recommend adding "run_at": "document_start" to the content script's configuration, so it fires earlier.

  2. Better yet, you don't need a content script. You could either rely on chrome.tabs events, or chrome.webNavigation API. You probably need the host permission (e.g. "*://*.youtube.com/*") for that to work (and "webNavigation" if you use it).

like image 51
Xan Avatar answered Feb 01 '26 02:02

Xan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!