首页 > 解决方案 > 如何从内容脚本向弹出脚本发送消息以显示在 popup.html 上

问题描述

****我正在制作一个谷歌扩展软件,我有一个在内容脚本文件上创建的数组,我想在 popup.html 上显示它的元素,在那里我创建了一个 div 元素来包含它们,我想要每个元素数组位于不同的 div 中。

//content script

var arr= [a,b,c,d];
//popup.html

<div class="showhere"></div>



//required popup.html to be

<div class="showhere">
      <div>a</div>
      <div>b</div>
      <div>c</div>
      <div>d</div>
</div>

我希望我可以通过示例获得解决方案,谢谢。****

标签: javascriptgoogle-chrome-extension

解决方案


弹出脚本,

    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
        if (request.subject == 'SOME_SUBJECT') {
            console.log(request.data);
            sendResponse("response");
        }
        else if (request.subject == 'OTHER_SUBJECT') {
            console.log(request.data);
            sendResponse("response");
        }
    });

内容脚本,

    chrome.runtime.sendMessage({
        subject: "SOME_SUBJECT",
        data: {
            name: "Roar"
        }
    }, function (response) { 
        console.log(response)
    });

推荐阅读