在我的一个组件中,当加载该组件时,我希望我的扩展程序将脚本注入(inject)到运行该扩展程序的当前选项卡中。该脚本本质上是获取源代码并将其保存为字符串。
因此,在我的 componentWillMount
中,我尝试以下列方式注入(inject)脚本...
componentWillMount() {
var result = '';
chrome.tabs.executeScript(null, {
file: './js/scripts/getPageSource.js'
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
result = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
我的脚本路径 ./js/scripts/getPageSource.js
与我的 React 应用程序正在使用的 index.html
文件相关。
我得到错误文件未找到,所以我更改了相对于组件的路径,但我仍然找不到文件。
我在想这可能不是通过 React 将脚本注入(inject)打开的选项卡的正确方法,是否有更好的方法?
编辑
这是我的 manifest.json
文件...
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_popup": "src/index.html"
},
"permissions": ["tabs", "<all_urls>"]
}
我的路径 ./js/scripts/getPageSource.js
位于上面引用的我的 src
文件夹中
最佳答案
使用相对于您的 manfest.json 文件的路径。
In Firefox, relative URLs are resolved relative to the current page URL. In Chrome, these URLs are resolved relative to the add-on's base URL.
从您的 manifest.json 来看,您的文件
应该是:
file: 'src/js/scripts/getPageSource.js'
关于javascript - 如何在 react 中使用 tabs.executeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474418/