I'm trying to build a hello world chrome extension using a template build from create-react-app.
I was able to create the chrome extension by adding a manifest:
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;
However, when I run npm run build
, I get this error:
/dev/hello-world/src/App.js 11:5 error 'chrome' is not defined no-undef
✖ 1 problem (1 error, 0 warnings)
How do I call chrome.runtime or pass a message from a react app to background.js?
This error is from ESLint, you could add the following line at the top of the file.
/*global chrome*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With