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

3

背景

我想创建一个Chrome扩展程序,当我点击扩展图标时,它会加载一个弹出窗口,该窗口会加载一个JavaScript文件。

我已经成功创建了一个仅包含HTML的弹出窗口,只需添加这两个文件即可:

manifest.json

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

popup.html

<html>
    ..
    hello world
</html>

问题

我希望能够加载Chrome 事件页面,以便弹出页面调用事件页面并与之交互。

我尝试过的方法

我在manifest.json中添加了以下内容:

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

并添加了一个简单的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');
  });
}

当我启动扩展并点击检查以查看Chrome开发工具时,控制台上什么也没有显示:

enter image description here

我也尝试将eventsPage.js的src添加到popup.html中:

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

但这并没有改变什么,我甚至无法在Chrome开发工具中找到eventsPage.js源代码。
我该怎么做?
1个回答

3
许多方法:
  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.


  1. 你正在混淆使用背景页和事件页,它们并不相同。背景页已经被弃用。
  2. 如果您能编写一些示例代码,那将非常好。
- abbood
@abbood,事实上,背景页面并没有被弃用,它只是用于不同的目的。我已经添加了一些简单的示例,对你来说应该是一个容易的任务(你在iOS方面有经验:)) - Haibara Ai
这是一个后续问题:http://stackoverflow.com/questions/41758616/getting-cannot-access-a-chrome-url-even-though-im-not-calling-it - abbood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接