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