首页 > 解决方案 > 如何将变量从后台脚本导入内容脚本?[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>" ]
}

标签: javascriptjquerygoogle-chrome-extension

解决方案


推荐阅读