javascript - 如何将变量从弹出窗口传递到内容脚本?
问题描述
如何将 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
}
这只是一个例子,我知道代码完全不正确
解决方案
您可以使用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
});
推荐阅读
- asp.net - asp.net UserControl 点击事件运行函数
- c# - 集成测试总是返回 500 状态码
- python - 输入字段和文本宽度
- python - 烛台图不显示
- c# - 如何在 UWP 中将 stackpanel 添加到 menuflyoutitem?
- reactjs - 使用 YARN 从私有注册表工件中提取依赖项
- javascript - 使用 React Native 对电话联系人进行排序
- python - 如何在python中使用列表进行拓扑排序
- javascript - 如何删除acf字段的重复结果以循环wordpress
- continuous-integration - CICD Java 应用程序(Maven)