0

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

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

我遇到的最大问题是 4)

清单.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": {}
}

背景.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 函数没有执行!你知道为什么以及如何解决它吗?

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

4

1 回答 1

1

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

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

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

由于Chrome 中的一个错误,您需要在执行脚本之前等待设置 URL
该错误已在 Chrome 100 中修复。

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)();
    }
  });
}

PSalert不能在 service worker 中使用。相反,您应该查看后台脚本的 devtools 控制台或使用chrome.notifications API。

于 2021-08-01T14:19:40.840 回答