2

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?

Community
  • 1
  • 1
shinzou
  • 5,850
  • 10
  • 60
  • 124

1 Answers1

6

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).

Xan
  • 74,770
  • 16
  • 179
  • 206
  • Thanks a lot, the first one works. The second one does not. It looks like you're very knowledgeable about chrome extensions so i want to consult you as I'm a total beginner, I want to make an extension that will close a youtube tab after the video has ended and that tab isn't focused for over a minute. How do you know what go to which script (content or background)? For example, Does YT events (https://developers.google.com/youtube/iframe_api_reference#Events) go to the content script? – shinzou Aug 25 '15 at 12:32
  • Also, do you have any tips or where to start for making that extension? – shinzou Aug 25 '15 at 12:32
  • Everyone should carefully read the [Overview page](https://developer.chrome.com/extensions/overview), it contains a lot of important information. SO can help if you have [well-defined questions](http://stackoverflow.com/help/how-to-ask). [This question](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) might be of use. – Xan Aug 25 '15 at 12:36