简体   繁体   English

如何从 chrome 扩展弹出窗口加载 JS

[英]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.我只是想创建一个 chrome 扩展,在其中单击扩展图标,它会加载一个加载 javascript 文件的弹出窗口。

I was able to do an html only popup simply by adding these two files:只需添加这两个文件,我就可以仅执行 html 弹出窗口:

manifest.json清单文件

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

popup.html弹出窗口.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.我想实际加载一个 chrome事件页面,以便弹出页面调用事件页面并与之交互。

what i have tried我试过的

I added this to manifest.json我将此添加到manifest.json

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

and added a simple eventsPage.js file:并添加了一个简单的eventsPage.js文件:

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:当我启动扩展程序并单击检查以查看 chrome 开发工具时.. 控制台上没有显示任何内容:

在此处输入图片说明

I've also tried adding the src of eventsPage.js to popup.html :我还尝试将eventsPage.js的 src 添加到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.但这没有任何改变,我什至无法在 chrome 开发工具中找到 eventsPage.js 源。

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添加一个例如popup.js的脚本并调用chrome.runtime.getBackgroundPage(function callback)与事件页面进行交互。

    popup.html弹出窗口.html

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

    popup.js弹出窗口.js

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

    eventsPage.js事件页面.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.由于您要在弹出页面和事件页面之间传输数据,因此还有许多其他解决方法,例如,我们可以使用全局存储(例如chrome.storage来保存/加载/响应更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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