首页 > 解决方案 > 如何将变量从弹出窗口传递到内容脚本?

问题描述

如何将 popup.html 输入中的变量传递给内容脚本填充?例如 popup.html

<body>
    <H1>MADE BY SK</H1>

    <input type="text" name="" id="nomeitem">Nome Item
    <input type="button" value="Guarda Valores" id="salvar" onclick="salvar()">
</body>

addtobasket.js

function salvar() {
    item_name = input("nomeitem").value
}

这只是一个例子,我知道代码完全不正确

标签: javascripthtml

解决方案


您可以使用chrome 消息服务,它允许您在注入内容脚本后传递值,或者您可以使用chrome.storage.local

使用 chrome 消息服务

在你的popup.js

salvar.addEventListener('click',()=>{
       
        chrome.tabs.query({active:true,currentWindow:true},(tabs)=>{
            chrome.tabs.sendMessage(tabs[0].id,{message: "hello"},(resp)=>{ //specify the message 
                var div=document.createElement('div')
                div.innerHTML=`<p class="text-warning">Notification ${resp.msg}</p>`
                document.body.appendChild(div)
            })
        })
   })

 },false)

在你的content.js

chrome.runtime.onMessage.addListener((request,sender,sendMessage)=>{
    value=request.message
//execute your code here 
 sendMessage({msg:'sent'})

使用 chrome.storage.local

在你的popup.js

chrome.storage.local.set({
    variable: data
},
 function () {
chrome.tabs.executeScript({
        file: "content.js"
    });
});

在你的content.js

chrome.storage.local.get("variable", function (data) {
          var getdata=data.variable
          // use getdata in your content script
  chrome.storage.local.remove("variable");// this is optional
});

推荐阅读