abbood
abbood

Reputation: 23558

how to load JS from a chrome extension popup

background

I simply want to create a chrome extension where I click on the extension icon, it loads a popup that loads a javascript file.

I was able to do an html only popup simply by adding these two files:

manifest.json

{
  ..    
  "browser_action": {
    "default_popup": "popup.html",
    ..
  }
}

popup.html

<html>
    ..
    hello world
</html>

problem

I want to actually load a chrome events page so that the popup page calls the events page and interacts with it.

what i have tried

I added this to manifest.json

  "background": {
    "scripts": ["eventsPage.js"],
    "persistent": false
  }

and added a simple eventsPage.js file:

chrome.runtime.onInstalled.addListener(onInit);
chrome.runtime.onStartup.addListener(onStartup);

function onInit() {
  console.log("on init");
}

function onStartup() {
  console.log("on startup");
}

if (chrome.runtime && chrome.runtime.onStartup) {
  chrome.runtime.onStartup.addListener(function() {
    console.log('on startup stuff');
  });
}

when I launch the extension and click on inspect to see chrome dev tools.. nothing shows up on the console:

enter image description here

I've also tried adding the src of eventsPage.js to popup.html:

</head> 
  ..
  <script src="eventsPage.js"></script>
  <body>
  ..

but that changes nothing, I can't even find the eventsPage.js source in chrome dev tools.

How do I do this?

Upvotes: 3

Views: 6057

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

Many ways:

  1. Add a script for example popup.js in popup.html and call chrome.runtime.getBackgroundPage(function callback) to interact with event page.

    popup.html

    ...
    <script src="popup.js"></script>
    ...
    

    popup.js

    chrome.runtime.getBackgroundPage(backgroundPage => backgroundPage.testMethod());
    

    eventsPage.js

    const testMethod = () => console.log('test');
    
  2. Use Message Passing(there are many examples in this link) to communicate with event page.

  3. Since you want to transfer data between popup page and event page, there are many other workarounds, for example, we could use global storage such as chrome.storage to save/load/react to changes.

Upvotes: 3

Related Questions