Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs chrome extension message passing not working

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?

like image 972
Jon Avatar asked Dec 27 '16 23:12

Jon


1 Answers

This error is from ESLint, you could add the following line at the top of the file.

/*global chrome*/
like image 96
Haibara Ai Avatar answered Sep 19 '22 07:09

Haibara Ai