这是继续:Script to close the current tab in Chrome
我现在正在尝试用扩展而不是 tampermonkey 脚本来做,我有 "matches": ["*://*.youtube.com/*", "*://youtube. com/*"],
在我的 list 文件中,而 js 脚本只是 chrome.tabs.remove(tab.id);
或 window.close();
但两者都不会关闭我打开的 youtube.com 页面。
难道也不能关闭带扩展的标签页?
最佳答案
chrome.tabs
不可用于内容脚本,因此如果它在您的代码中,它会失败并出现异常。
window.close
有一个警告:
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.
我不确定它是否适用于内容脚本 - 但假设适用。
您可以通过添加后台脚本(可以访问 chrome.tabs
)使其工作,并从那里检测导航,或者只是从上下文脚本向后台脚本发送消息来执行此操作。
后台消息:
// 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); });
我建议将
"run_at": "document_start"
添加到内容脚本的配置中,以便它更早触发。更好的是,您不需要内容脚本。您可以依赖
chrome.tabs
事件或chrome.webNavigation
API。您可能需要主机许可(例如"*://*.youtube.com/*"
)才能正常工作(如果您使用它,还需要"webNavigation"
) .
关于javascript - 扩展程序可以关闭选项卡吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201846/