将选项卡导航到 URL 并在其中执行脚本

问题描述 投票:0回答:1

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

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

我遇到的最多问题是 4)

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

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

google-chrome-extension chrome-extension-manifest-v3
1个回答
1
投票

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

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

请注意,导航到具有不同来源的 URL 后,

activeTab
权限将不适用于选项卡,因为此权限仅适用于当前显示的来源。

由于Chrome中的bug,您需要等待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
不能在 Service Worker 中使用。相反,您应该查看后台脚本的 devtools 控制台 或使用 chrome.notifications API。

© www.soinside.com 2019 - 2024. All rights reserved.