简体   繁体   中英

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:

在此处输入图片说明

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM