[英]How to use chrome API in React.js Chrome Extension
我开发了一个作为 Chrome 扩展的 React 应用程序(生产 index.html 成为 Chrome 扩展manifest.json
中的default_popup
html 页面。json )
但是,我需要访问 chrome API 并且我无法在我的 react 应用程序中使用它,因为该应用程序既不是 background.js 也不是内容脚本。 为了使我的 React 应用程序能够访问 Chrome API,我需要做什么?
我不确定这是最好的解决方案,但它是解决方案之一:您可以使用 build 命令完成 react 项目并仅使用 build 文件夹作为 chrome 扩展:
完成 UI(反应部分)后,请执行以下操作:
npm run build
go 构建文件夹并将manifest.json更改为如下所示:
{
"manifest_version": 2,
"short_name": "React App",
"name": "Create React App Sample",
"description": "google chrome extension",
"version": "1.0",
"browser_action": {
"default_icon": "favicon.ico",
"default_popup": "index.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
在background.js中你可以做任何你想做的事情......
如果你认为弹出页面不能使用 Chrome API,那你就错了。 弹出页面与后台脚本在相同的上下文中运行,因此对 Chrome API 具有相同的访问权限。 因此,如果您的扩展程序只应该包含弹出页面,您可以直接从弹出窗口中调用 Chrome API。
但是,如果您还想使用背景和/或内容脚本并在同一构建过程中构建所有这些扩展组件,则必须修改 CRA 的构建配置以使其支持多个入口点和扩展所需的其他内容。 幸运的是,有一个自定义 CRA 模板 - complex-browserext
,它可以完成 chrome 扩展所需的所有自定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.