从 Chrome 扩展中的内容脚本访问全局对象 [英] Accessing global object from content script in chrome extension
问题描述
我在 .js 文件中定义了一个全局对象.例如 file1.js 包含全局对象 SomeObject.这个文件被加载到 background.html 中.
I have defined a global object in a .js file. For example file1.js contains the global object SomeObject. This file gets loaded in background.html.
由于file1.js 包含在background.html 中,我可以访问此页面中的全局对象.所以这里没有问题.
Since file1.js is included in background.html, I am able to access the global object in this page. So no issues here.
当执行像单击扩展按钮这样的事件时,我正在使用 chrome.tabs.executeScript(null, {file: "contentscript.js"});
api 运行内容脚本.
When an event like click on the extension button is performed, I am running a content script using the chrome.tabs.executeScript(null, {file: "contentscript.js"});
api.
在这种情况下,我如何访问 contentscript 中的 SomeObject?
How can I access SomeObject in the contentscript in this case?
推荐答案
没有办法直接访问后台页面的全局对象内容脚本 或注入脚本.
There is no way to get direct access to the background page's global object from a Content script or injected script.
要从注入的脚本中使用后台页面的方法,请按照下列步骤操作:
To use a background page's method from an injected script , follow these steps:
- 内容脚本:将事件侦听器绑定到页面示例 1.
每当你想从后台页面通知方法时: - 注入脚本:创建并触发此特定事件示例 1.
→来自 1) 的事件侦听器被触发. - 在此事件侦听器中,使用
chrome.runtime.sendMessage代码>
从后台请求功能示例2. - 在后台页面中,使用
chrome.runtime 处理此请求.onMessage
. - 或者,使用
chrome.tabs 在原始选项卡中注入代码.executeScript(tab.id, func)
.
- Content Script: Bind an event listener to the page example 1.
Whenever you want to notify the method from the background page: - Injected script: Create and fire this specific event example 1.
→ The event listener from 1) gets triggered. - In this event listener, use
chrome.runtime.sendMessage
to request the functionality from the background example 2. - In the background page, handle this request using
chrome.runtime.onMessage
. - Optionally, inject code in the original tab using
chrome.tabs.executeScript(tab.id, func)
.
要使用内容脚本中的背景页面方法,只需执行第 3 步和第 4 步.
下面是一个示例,其中内容脚本与后台页面通信:
To use a background page's method from a Content script, only steps 3 and 4 are needed.
Here's an example, in which the content script communicates with the background page:
// Example background page
function some_method(arg_name) {
return localStorage.getItem(arg_name);
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.type == 'localStorage - step 4') {
callback( some_method(request.name) );
} else if (request.type == 'localStorage - step 5') {
localStorage.setItem(request.name, request.value);
}
});
// Example contentscript.js
chrome.runtime.sendMessage({
type: 'localStorage - step 4',
name: 'preference'
}, function(value) {
if (value === null) {
// Example: If no preference is set, set one:
chrome.runtime.sendMessage({
type: 'localStorage - step 5',
name: 'preference',
value: 'default'
});
}
});
另见
- SO:您应该了解背景知识脚本 vs 内容脚本 vs 注入脚本.
- SO:示例代码:在注入脚本和内容脚本之间进行通信.
这篇关于从 Chrome 扩展中的内容脚本访问全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!