chrome.tabs.executeScrip To chrome.scripting.executeScript

2023-12-28 17:37:20

问:

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.

文章来源:https://blog.csdn.net/glc22/article/details/135273661
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。