admin管理员组

文章数量:1307006

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/*", "*://youtube/*"], 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 page that I open.

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

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./*", "*://youtube./*"], 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. page that I open.

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

Share Improve this question edited May 23, 2017 at 12:29 CommunityBot 11 silver badge asked Aug 25, 2015 at 10:41 shinzoushinzou 6,23215 gold badges73 silver badges137 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 remend 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./*") for that to work (and "webNavigation" if you use it).

本文标签: javascriptCan an extension close a tabStack Overflow