javascript - 返回值 background.js 到 content.js
问题描述
Helo,这个用于 chrome 扩展的 javascript,如何将值从 background.js 获取到内容 js。
{
"manifest_version":2,
"permissions": [
"storage",
"activeTab",
"contextMenus"
],
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["jquery.js","content.js"],
"css": ["style.css"]
}...
"background": {
"persistent": false,
"scripts": ["background.js"]
}
}
那是我的 json 文件,我有这个问题,这个我的 background.js
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({
id: "right_down",
title: "Grab-Image to Content Creator",
contexts: ["image"],
onclick: cow
});
});
var cow = chrome.contextMenus.onClicked.addListener(function(info,tab) {
// return
cow = info['srcUrl'];// i want Displays "url image" and proces it to content.js.
console.log(url);
});
这对于 content.js
chrome.runtime.getBackgroundPage(function (backgroundPage) {
console.log(backgroundPage.cow); //get value url image
});
我运行它但没有得到任何东西,如何将返回表单背景返回到其他文件?
解决方案
在你的 background.js 中,你可以chrome.tabs.sendMessage
像下面这样使用:
chrome.contextMenus.onClicked.addListener((info, tab) => {
chrome.tabs.sendMessage(tab.id, {
url: info['srcUrl'],
});
});
它会将对象数据(包含您的 url)发送到给定的选项卡(由 tab.id 指定)。您可以使用循环发送到所有选项卡。
在内容脚本中,您可以通过以下方式从后台接收数据:
chrome.runtime.onMessage.addListener((request) => {
let {
data,
} = request;
console.log(data);
});