2

I am building a chrome extension, which uses react/webpack, and it needs to inject code into an existing page. So I need to load one of my javascript files when the component is rendered.

However, I cannot access properties in that javascript file. I get error 'Cannot read properties of undefined (reading 'initialvalue')'. I have given the manifest.json file all the proper permissions and I know the script file is loading correctly. What am I doing wrong?

plugin.bundle.js (javascript file I'm trying to load)

var plugin = plugin || {};

SetupPlugin();
function SetupPlugin() {
    plugin.initialvalue = plugin.initialvalue || 123;
}

index.jsx

import { render } from 'react-dom';
import Embedtab from './Embedtab';

render(<Embedtab />, window.document.body.querySelector('.someclass'));

Embedtab.tsx

declare global {
  interface Window {
    plugin: any;
  }
}

export class Embedtab extends React.Component<any> {
  componentDidMount() {
    const script = document.createElement("script");
    script.src = chrome.runtime.getURL("./../plugin.bundle.js");
    script.async = false;
    script.onload = () => this.scriptLoaded();

    document.body.appendChild(script);
  }

  scriptLoaded() {
    alert("embedded loaded, value is " + window.plugin.initialvalue); //errors here
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          Hello World
        </header>
      </div>
    );
  }
};

export default Embedtab;
Alienator
  • 185
  • 2
  • 9
  • Content scripts are isolated from scripts that run in the page like your plugin.bundle.js ([more info](https://stackoverflow.com/a/9517879)). Why do you run this script this way instead of including the code directly? – wOxxOm May 28 '22 at 05:11

0 Answers0