javascript - 如何将变量从后台脚本导入内容脚本?[Chrome 扩展程序]
问题描述
现在我的背景脚本是:
function idInfo() {
var idPage = "https://www.supremenewyork.com/shop/" +itemID+ ".json";
$.getJSON(idPage, function(data) {
idData = data.styles;
console.log(idData);
var colorInfo = idData.find(element => element.name == getItemColor);
console.log(colorInfo);
colorID = colorInfo.id;
console.log("!!! COLOR ID FOUND\t" + colorID + "\t!!!")
var sizesData = colorInfo.sizes;
console.log(sizesData);
var sizeInfo = sizesData.find(element => element.name == getItemSize);
console.log(sizeInfo);
sizeID = sizeInfo.id;
console.log("!!! SIZE ID FOUND\t" + sizeID + "\t!!!")
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {sizeID: sizeID}, function() {
console.log("Settings saved");
});
});
addToCart();
});
}
function addToCart() {
var atcPage = "https://www.supremenewyork.com/shop/mobile/" +itemID+ "/" +colorID;
chrome.tabs.create({
url: atcPage
})
}
我的内容脚本是(在后台脚本中指向您的 atcPage 时处于活动状态):
chrome.runtime.onMessage.addListener(function({sizeID}) {
function clickAdd() {
document.querySelector('input[name="commit"]').click();
}
function select(id, value) {
let element = document.getElementById(id);
element.value = value;
clickAdd();
}
select("s", sizeID);
});
我相信我做错了什么,我正在尝试将 sizeID 变量从我的后台脚本导入到我的内容脚本,我该怎么做?现在我正在尝试在背景上执行 chrome.tabs.query 并在内容脚本上执行 chrome.runtime.onmessage 但它不起作用(猜测我做错了什么)
{
"name": "supreme",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["https://www.supremenewyork.com/"],
"js": ["jquery-3.4.1.min.js"]
},
{
"matches": ["https://www.supremenewyork.com/shop/mobile/*"],
"js": ["jquery-3.4.1.min.js", "getToken.js"]
}
],
"background": {
"scripts":
[
"content.js", "jquery-3.4.1.min.js"
]
},
"browser_action": {
"default_popup": "popup.html",
"default_title": "Popup",
"default_icon": "suppic.png"
},
"permissions": [ "webRequest", "webRequestBlocking", "unlimitedStorage", "tabs", "notifications", "tabCapture", "https://*.supremenewyork.com/", "background", "activeTab", "<all_urls>" ]
}
解决方案
推荐阅读
- python - 使用枚举的 for 循环意外终止
- android - 我的 Sip 应用程序中的 SipVicious(100) 来电
- python - 如何将存储在 6 行中的变量列表合并到一个列表中并消除空列表
- javascript - 从 iframe 返回时重新加载页面
- postgresql - PostgreSQL 中 CASE 表达式中的子查询
- java - 按下删除按钮后,如何从输入到我的 textView 的数据库中删除值?
- android - Gradle 文件错误地更改了 android
- python - 如何在我的代码中使用具有特定值的第一个单元格
- c# - 如何修改基于表达式的过滤器以避免在 Entity Framework Core 3.0 中进行客户端评估
- c# - 使用组和连接在两个索引表上与一个组合选择的单独 LINQ2SQL 选择的性能