Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension content script not injecting to the DOM when built with ReactJS

I'm trying to build a chrome extension using React. I've ejected create-react-app and have made necessary changes to emit content.chunk.js which is included in manifest.json as below

{
  "manifest_version": 2,
  "version": "0.0.1",
  "name": "My extension",
  "description": "Some description",
  "permissions": [],
  "browser_action": {
    "default_title": "My extension",
    "default_popup": "index.html"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "css": ["/static/css/content.chunk.css"],
    "js": ["/static/js/content.chunk.js"]
  }]
}

my content.js

import React from 'react';
import ReactDOM from 'react-dom';
import Main from 'extensionContainers/Main';

alert('bazooka!');
const app = document.createElement('div');
app.id = "extension-root";
document.body.appendChild(app);

ReactDOM.render(<Main />, app);

after build, when I load my extension this doesn't do anything. However, when I edit the contents of content.chunk.js generated by webpack to alert("something"), the extension works fine and shows alert on every URL.

Why is my react code isn't doing anything? There are no error logs.

like image 375
Vishal Sharma Avatar asked Jan 26 '23 00:01

Vishal Sharma


1 Answers

Answering my own question if anyone else stumbles upon this.

So, I realized that the Webpack config from [email protected] ejection had code split configurations enabled. Which was splitting react library code from my code making it inexecutable.

Here are the settings I changed in the webpack config to get it working. (note that this is only advisable to do when developing chrome extension)

In webpack.config.js remove the configuration for splitChunks under optimization node, and set runtimeChunk to false.

...
optimization: {
  .
  .
  // remove spitChunks config
  splitChunks: {
     chunks: 'all',
     name: false,
  },
  runtimeChunk: true, // set this to false
}
...

the generated bundle will now be named as content.js (considering content as the entry point) link this content.js in your manifest.json under content_scripts and you're good to go.

like image 176
Vishal Sharma Avatar answered Feb 12 '23 12:02

Vishal Sharma