我正在尝试使用create-react-app的模板构建来构建一个hello world chrome扩展。
我可以通过添加清单来创建Chrome扩展程序:
manifest.json
{
"manifest_version": 2,
"name": "Demo React-Chrome extension",
"description": "This extension shows how to run a React app as a Chrome extension",
"version": "1.0",
"permissions": [
"debugger",
"activeTab",
"tabs",
"background",
"https://*/",
"http://*/"
],
"browser_action": {
"default_icon": "favicon.ico",
"default_popup": "index.html"
},
"background": {
"scripts":["background.js"]
}
}
background.js
:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message);
switch(message.action){
case "popupOpen":{
console.log('popup is open');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
}
break;
}
});
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {showHeader: true};
this.handleClick = this.handleClick.bind(this);
chrome.runtime.sendMessage({action: "popupOpen"}).bind(this);
}
handleClick() {
console.log('clicked');
this.setState( prevState => ({
showHeader: !prevState.showHeader
}));
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{this.state.showHeader && <h2>Welcome to React Jon</h2>}
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<button onClick={this.handleClick}>
{this.state.showHeader ? "HIDE" : "SHOW"}
</button>
</div>
);
}
}
export default App;
但是,当我运行npm run build
时,我收到此错误:
/dev/hello-world/src/App.js 11:5错误'chrome'未定义 无是undef
✖1个问题(1个错误,0个警告)
如何调用chrome.runtime或将反应应用中的消息传递给background.js?
答案 0 :(得分:22)
此错误来自ESLint,您可以在文件顶部添加以下行。
/*global chrome*/
答案 1 :(得分:0)
为了澄清,错误是由create-react-app
的编译错误引起的。它不允许构建中出现ES Lint
错误。
接受的答案很棒,您也可以这种方式添加评论(此ES Lint规则称为no-undef
):
/* eslint-disable-rule no-undef */
chrome.blah()
/* eslint-enable-rule no-undef */
我有这个VS Code扩展,我选择了很长的路,这太棒了: https://marketplace.visualstudio.com/items?itemName=drKnoxy.eslint-disable-snippets
我推荐它,因为很容易记住输入esl
并从片段中选择,比记住各种禁用规则的方法要容易得多。