chrome 传递给内容脚本的扩展命令

chrome extension command passing to content script

我想在我的内容脚本中实现一个触发函数的热键。 内容脚本 (main.js) 在我的 popup.js 文件的页面上执行。

我已将命令添加到我的 manifest.json 中,当我将 onCommand 侦听器添加到我的 popup.js 时,我可以控制台记录它在我按下热键 (Ctrl+Shift+K) 时被触发)

但是我无法将其传递到我的内容脚本。

manifest.json

{
    "manifest_version": 2,
    "name": "Ccghjj",
    "description": "hdjdjdjsjs",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": ["tabs", "*storage", "activeTab"],
    "content_scripts": [
        {
            "matches": ["*://"],
            "css": ["style.css"],
            "js": ["jquery.js", "main.js"]
        }
    ],
    "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
    "web_accessible_resources": ["toolbar.html", "style.css"],
    "commands": {
        "show_deals": {
            "suggested_key": {
                "default": "Ctrl+Shift+K"
            },
            "description": "Highlight Deals"
        }
    }
}

popup.js

function registerButtonAction(tabId, button, action) {
    // clicking button will send a message to
    // content script in the same tab as the popup
    button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}

function setupButtons(tabId) {
    // add click actions to each 3 buttons
    registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
    registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
    registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}

function injectStartSearchScript() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        // Injects JavaScript code into a page
        // chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });

        // add click handlers for buttons
        setupButtons(tabs[0].id);
    });
}

injectStartSearchScript();


// hotkey command listener
chrome.commands.onCommand.addListener((show_deals) => {
    console.log(`Command "${show_deals}" triggered`);
    // how can I get to main.js to call deals()

});

main.js(内容脚本)

async function deals() {
    // should be fired when I press my hotkey Ctrl+Shift+K

使用如下消息

popup.js

chrome.commands.onCommand.addListener((show_deals) => {
    console.log(`Command "${show_deals}" triggered`);
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tab.id, { msg: "deals"})
    })
});

并在您的内容脚本中

if (!window.firstTimeExecuted) {
    window.firstTimeExecuted = true;
    chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
        if (data.msg == 'deals') {
            deals()
        }
    });
}