chrome.tabs.executeScrip To chrome.scripting.executeScript

问:

chrome.tabs.executeScript(null, { code: `token = '${token}';` }, () => chrome.tabs.executeScript(null, {file: 'js/hook.js'})); //在需要时注入到页面中 转 chrome.scripting.executeScript

gpt:

In Manifest V3, you can replace `chrome.tabs.executeScript` with `chrome.scripting.executeScript`. Here's how you can modify your code:

```javascript
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  const activeTab = tabs[0];
  if (activeTab) {
    chrome.scripting.executeScript({
      target: { tabId: activeTab.id },
      function: (token) => {
        // This code runs in the context of the page
        window.token = token;
      },
      args: [token],
    }, () => {
      // This code runs after the script has been executed
      chrome.scripting.executeScript({
        target: { tabId: activeTab.id },
        files: ['js/hook.js'],
      });
    });
  }
});
```

In this example:

- `chrome.scripting.executeScript` is used to execute a script in the context of the active tab.
- The first `executeScript` call sets the `token` variable in the context of the page.
- The second `executeScript` call injects the `js/hook.js` file into the page.

Remember to handle the logic in `js/hook.js` accordingly, and ensure that the necessary permissions are set in your manifest file.

你可能感兴趣的:(chrome,前端,javascript)