Chrome扩展程序-将变量从HTML文件传递到.js文件 [英] Chrome Extension - Passing variables from HTML file to .js file
问题描述
我正在尝试将Chrome扩展程序的HTML中的变量传递到content_script.js文件中.第一次使用javascript,所以我很迷路.我已经尝试了一些方法,但是似乎都没有用.这是我最近的尝试:
I am trying to pass a variable from the HTML of my Chrome extension into my content_script.js file. First time using javascript so I'm pretty lost. I have tried a few things but none of them seem to work. Here is my latest attempt:
popup.html
popup.html
<html>
<head><title>activity</title></head>
<body>
<input id="email" type="email" placeHolder="Email" /> <br />
<button id="clickactivity">Create Account</button> <br />
<script src="popup.js"></script>
</body>
</html>
popup.js
function injectTheScript() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
// query the active tab, which will be only one tab
//and inject the script in it
chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
});
}
document.getElementById('clickactivity').addEventListener('click', injectTheScript);
content_script.js
content_script.js
function registerAccount() {
regEmail = document.getElementById("email");
document.getElementById("register-email").value=regEmail.value;
}
registerAccount();
推荐答案
您的内容脚本和弹出脚本在不同的文档上运行:您不能直接从另一个文档中访问其中一个的变量.
Your content script and your popup script run on different documents: you cannot access a variable of one of them from the other directly.
尝试一下:
popup.js
document.getElementById('clickactivity').onclick = () => {
chrome.tabs.executeScript({code: `
var inputToFill = document.getElementById('register-email');
if (inputToFill) inputToFill.value = '${document.getElementById('email').value}';
`});
};
其他选项可能正在使用消息或通过
Other options may be using messaging or synchronisation through storage.
这篇关于Chrome扩展程序-将变量从HTML文件传递到.js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!