how to load JS from a chrome extension popup

六眼飞鱼酱① 提交于 2020-01-04 06:31:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41756849/how-to-load-js-from-a-chrome-extension-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!