如何从Chrome扩展程序的弹出窗口访问后台页面中的对象

How to access to object in background page from popup in Chrome extension

本文关键字:后台 访问 对象 窗口 Chrome 扩展 程序      更新时间:2023-09-26

在我正在开发的Chrome扩展程序中,我想在单击弹出窗口时访问在后台页面中创建和维护的数据结构。不幸的是,我是Javascript和Chrome扩展开发的新手,你能告诉我怎么做吗?这是否涉及弹出窗口和后台页面之间的消息传递?谢谢。

您可以从弹出窗口中编写三个这样的文件来访问后台的数据结构.html.html:


//in popup.html
<script type="text/javascript" src="mainscript.js"></script>
<!-- JavaScript and HTML must be in separate files for security. -->

//in mainscript.js
chrome.extension.getBackgroundPage().data = 'your data';

//in background.html
<script type="text/javascript">
var data;
</script>

你需要像这样的 manifest.json(也许使用 browser_action 而不是 page_action):

....
,
"background_page": "background.html",
"page_action": {
    "default_icon": "your_icon.ico",
    "default_title": "Your title",
    "default_popup": "popup.html"
  },
....

编辑:有关在Chrome扩展程序中传递消息的信息,请参阅以下功能

http://code.google.com/chrome/extensions/extension.html#method-sendRequest

http://code.google.com/chrome/extensions/extension.html#event-onRequest

以及这个有用的描述:

http://code.google.com/chrome/extensions/messaging.html