javascript - 扩展程序可以关闭选项卡吗?

标签 javascript google-chrome google-chrome-extension

这是继续: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)使其工作,并从那里检测导航,或者只是从上下文脚本向后台脚本发送消息来执行此操作。

  1. 后台消息:

    // 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" 添加到内容脚本的配置中,以便它更早触发。

  2. 更好的是,您不需要内容脚本。您可以依赖 chrome.tabs 事件或 chrome.webNavigation API。您可能需要主机许可(例如 "*://*.youtube.com/*")才能正常工作(如果您使用它,还需要 "webNavigation") .

关于javascript - 扩展程序可以关闭选项卡吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201846/

相关文章:

javascript - 在chrome扩展中通过本地文件发送数据查询

javascript - Chrome 扩展 DOM 已完全加载

javascript - 如何更改在不同对象中复制的 JSON 的引用

javascript - jQuery 不从 outlook.com 中删除元素

javascript - 努力使用 for 循环向对象添加属性

javascript - 使用 on() 方法获取当前对象

ios - Font-awesome 字体渲染不一致

python - scrapy xpath 为什么这个页面是空的,但我可以在 chrome f12 工具中看到它?

python - 被带有 selenium 和 chromedriver 的网站阻止

google-chrome-extension - 如何在多个选项卡中保持 Chrome 扩展同步