首页 > 解决方案 > Chrome 扩展程序:在执行其他功能之前等待 sendMessage 响应?

问题描述

我的上下文菜单扩展中有两个功能。我必须单击一个才能向内容脚本发送消息,然后我必须单击另一个,因为 sendMessage 函数在我的后台脚本中设置了变量。我想要做的只是让它们成为一个按钮并让 sendMessage 函数首先返回,然后另一个函数可以做到这一点,因为现在变量已设置。这就是我的意思:

在后台.js

chrome.contextMenus.create({
    title: "Send Message",
    contexts: ["all"],
    onclick: sendMessage
});

chrome.contextMenus.create({
    title: "Get All",
    contexts: ["all"],
    onclick: getAll
});

var title;
var link;
var bp;
var imgSrc;

function sendMessage() {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            req: "request"
        }, function (response) {
            console.log("responded");
            title = response.title;
            link = response.link;
            bp = response.bp;
            imgSrc = response.imgSrc;
        });
    });
};

function getAll(info) {
    var el = document.createElement('textarea');
    var all =
        "<tr><td><img src=\"" + imgSrc + "\"></td>\n\
        <td><span class =\"productTitle\">" + title + "</span></td>\n\
        <td>" + bp.split("\n").slice(0, 5).map(i => '<span class="bulletPoints"><i class="fas fa-check" style="color: #5cb85c"></i> ' + i.substring(0, 90) + "...</span>").join("\n") + "</td>\n\
        <td>[boombox_button tag_type=\"a\" type=\"success\" url=\"" + info.pageUrl.substring(0, link.indexOf("dp") + 14) + "\" target=\"blank\"]Check Price[/boombox_button]</td></tr>";
    el.value = all;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
}

在 content.js 中

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
    if (request.req == "request")
        sendResponse({
            title: document.getElementById("productTitle").innerText,
            link: window.location.href,
            bp: document.getElementById("feature-bullets").innerText,
            imgSrc: document.getElementById("imgTagWrapperId").getElementsByTagName('img')[0].src.toString().replace(/_.*_/, '_SX250_')
        });
    return true;
});

我对 Javascript 还是很陌生,并且一直在尝试不同的东西,比如回调、承诺、setTimeout,我不确定我是否正确设置它们,但我希望有人能指出我正确的方向。

标签: javascriptgoogle-chrome-extensioncallbackasync-awaitmessaging

解决方案


推荐阅读