Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack and programmatically injected content scripts

I'm developing a Chrome extension using React and Webpack.

In this project, different modules will programmatically inject content scripts using chrome.tabs.executeScript(null, {file: 'content-script-file.js'}).

This becomes problematic since I'm using Webpack for bundling everything. Basically, the background script is loading a number of modules, which are all configured to inject content scripts programmatically under certain circumstances.

However, I can't figure out how these content scripts will be "found" in the bundled application. They aren't ever explicitly imported, just referenced in executeScript calls.

At the same time, the content scripts use React, so they have to go through the babel-loader in Webpack.

Any ideas?

like image 574
damd Avatar asked Nov 24 '15 11:11

damd


1 Answers

Your content scripts are effectively "entry points" in webpack-terms.

Each top-level content script should be defined as a webpack entry. Use webpack to build these content scripts. Each entry will pull in all of its dependencies (like React) into one big blob.

You then make a 2nd webpack build that builds your extension. This extension will use the raw loader and import your webpack-compiled content scripts and then it will have them all as strings local variables:

import scriptA from 'content/build/a';
import scriptB from 'content/build/b';

And now you can inject the scripts into your tabs as needed:

chrome.tabs.executeScript(null, scriptA);
like image 189
Brandon Avatar answered Nov 15 '22 22:11

Brandon