Chrome扩展程序js:在background.js和popup.js之间共享功能 [英] Chrome Extension js: Sharing functions between background.js and popup.js

查看:111
本文介绍了Chrome扩展程序js:在background.js和popup.js之间共享功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个JavaScript函数 foo(),该函数要在后台和 popup.html 中执行.

Suppose I have a JavaScript function foo() which I want to execute in both the background and in popup.html.

例如:它在我的Chrome扩展程序的后台每小时执行一次,但也可以由用户在单击按钮时从弹出菜单( popup.html )激活.

For example: it is executed every hour in the background of my Chrome extension, but can also be activated by the user from the popup menu (popup.html) on a button click.

我目前有一个 global.js 脚本,用于定义 foo(),并且当我在中包含对 foo()的调用时> popup.js 文档,它们执行没有问题.(如果我将两个脚本都包含在 popup.html 中)

I currently have a global.js script which defines foo() and when I include calls to foo() in my popup.js document, they execute without issue. (If I include both scripts in popup.html)

但是,当我尝试访问 background.js 中的 foo()时,调用不会执行(即使 global.js 包含在背景""manifest.json"扩展文件中:

However, when I try to access foo() inside background.js, the calls do not execute (even if global.js is included in the "background" "manifest.json" extension file:

"background": {
    "persistent": true,
    "scripts": ["background.js", "global.js"]
},

是否有一种方便的方法可以在 background.js popup.js 之间共享功能(而无需将整个功能都复制到每个函数中)?

Is there a convenient way to share functions between background.js and popup.js (without copying the entire function into each)?

推荐答案

后台脚本以清单文件中指定的顺序加载.只需在后台脚本之前使用通用代码加载文件,如下所示:

The background scripts are loaded in the order specified in the manifest file. Simply load the file with common code before your background script as follows:

"background": {
    "persistent": true,
    "scripts": ["global.js", "background.js"]
},

您也可以使用 chrome,而不是在弹出窗口中复制代码.从弹出窗口中访问extension.getBackgroundPage() 来访问背景页面的函数/变量,例如 chrome.extension.getBackgroundPage().myFunction(); .

Instead of duplicating the code in the popup, you can also use chrome.extension.getBackgroundPage() from the popup to access functions/variables of the background page, e.g. chrome.extension.getBackgroundPage().myFunction();.

这篇关于Chrome扩展程序js:在background.js和popup.js之间共享功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆