【问题标题】:Navigate tab to a URL and execute script inside将选项卡导航到 URL 并在其中执行脚本
【发布时间】:2021-10-07 04:39:39
【问题描述】:

我正在努力让这个简单的 f-ty 工作......我的情况是:

  1. 获取当前网址
  2. 修改它
  3. 导航/重定向到它
  4. 在那里执行自定义 JS 代码

我遇到的最多问题是 4)

ma​​nifest.json

{
  "name": "Hello, World!",
  "description": "Navigate and execute custom js script",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "tabs",
    "activeTab",
    "scripting"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {}
}

background.js

function myCustomScript() {
    alert('myCustomScript test ok!');
    console.log('myCustomScript test ok!');
}

chrome.action.onClicked.addListener((tab) => {

    chrome.tabs.update({url: "https://example.com"}, myCustomScript);

});

页面被重定向但我的js函数没有执行!你知道为什么以及如何解决它吗?

P.S:这是我第一次创建我的 chrome 扩展,也许我做错了什么......

【问题讨论】:

    标签: google-chrome-extension chrome-extension-manifest-v3


    【解决方案1】:

    要执行自定义代码,请使用chrome.scripting API。对于这种情况,您需要:

    1. "scripting" 添加到 "permissions",您已经拥有了,
    2. "https://example.com/" 添加到 manifest.json 中的 "host_permissions"

    请注意,activeTab 权限在标签导航到具有不同来源的 URL 后将不适用于标签,因为此权限仅适用于当前显示的来源。

    由于bug in Chrome,需要等待URL设置好后才能执行脚本

    chrome.action.onClicked.addListener(async tab => {
      await chrome.tabs.update(tab.id, {url: "https://example.com"});
      // Creating a tab needs the same workaround
      // tab = await chrome.tabs.create({url: "https://example.com"});
      await onTabUrlUpdated(tab.id);
      const results = await chrome.scripting.executeScript({
        target: {tabId: tab.id},
        files: ['content.js'],
      });
      // do something with results
    });
    
    function onTabUrlUpdated(tabId) {
      return new Promise((resolve, reject) => {
        const onUpdated = (id, info) => id === tabId && info.url && done(true);
        const onRemoved = id => id === tabId && done(false);
        chrome.tabs.onUpdated.addListener(onUpdated);
        chrome.tabs.onRemoved.addListener(onRemoved);
        function done(ok) {
          chrome.tabs.onUpdated.removeListener(onUpdated);
          chrome.tabs.onRemoved.removeListener(onRemoved);
          (ok ? resolve : reject)();
        }
      });
    }
    

    附: alert 不能在服务工作者中使用。相反,您应该查看devtools console of the background script 或使用chrome.notifications API。

    【讨论】:

    • 由于某种原因它说:“服务工作者注册失败”......即使我离开 chrome.action.onClicked.addListener(async tab => {})();从您的所有代码中 - 它显示错误...
    • 有一个错字:()。对于那个很抱歉。答案已更新。
    • 你有什么版本的chrome?
    • 当前版本为92。
    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 2020-03-28
    • 1970-01-01
    • 2018-02-01
    • 2017-05-19
    • 1970-01-01
    相关资源
    最近更新 更多