bum*_*una 2 javascript google-chrome google-chrome-extension
我有 popup.js 脚本:
function FireInjectionScript() {
//Want to Pass this variable.
var updateTextTo = document.getElementById('mat_no').value.trim()
chrome.tabs.executeScript({
file: 'InjectionScript.js'
});
}
document.getElementById('caseButton').addEventListener('click', FireInjectionScript);
Run Code Online (Sandbox Code Playgroud)
我已经浏览了 google 和 stackoverflow 前 5 页中的几乎所有问题,但无法让这个简单的参数传递工作。
已经尝试过这个,这个,这个。许多问题都是相当古老的。这在 Chrome 中不再可能了吗?我的最终目标是传递变量,然后从 WebApi 返回数据,以根据传递的变量填写页面上的一些控件 - 我是不是找错树了。非常感谢任何指导。
您可以使用消息传递将数据发送到注入的脚本,但您需要选项卡 ID。
弹出窗口.js
function FireInjectionScript() {
//Want to Pass this variable.
var updateTextTo = document.getElementById('mat_no').value.trim();
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
chrome.tabs.executeScript(tabs[0].id,{file: 'InjectionScript.js'},()=>{
chrome.tabs.sendMessage(tabs[0].id,{myVar:updateTextTo});
});
});
}
document.getElementById('caseButton').addEventListener('click', FireInjectionScript);
Run Code Online (Sandbox Code Playgroud)
InjectionScript.js
chrome.runtime.onMessage.addListener(message=>{
if (message.myVar) {
//here you can access message.myVar
}
});
Run Code Online (Sandbox Code Playgroud)