4
我試圖使用從create-react-app構建的模板來構建hello世界Chrome擴展。reactjs 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 error 'chrome' is not defined no-undef
✖ 1 problem (1 error, 0 warnings)
如何調用chrome.runtime或從反應應用background.js傳遞消息?
太棒了。要清楚,我將它添加到App.js文件的頂部,並且它工作正常。 – Jon