我正在尝试将Chrome扩展程序的HTML中的变量传递到content_script.js文件中。第一次使用javascript,所以我很迷路。我已经尝试了一些方法,但是似乎都没有用。这是我最近的尝试:
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
function registerAccount() {
regEmail = document.getElementById("email");
document.getElementById("register-email").value=regEmail.value;
}
registerAccount();
答案 0 :(得分:1)
您的内容脚本和弹出脚本在不同的文档上运行:您不能直接从另一个文档中访问其中一个的变量。
尝试一下:
popup.js
document.getElementById('clickactivity').onclick = () => {
chrome.tabs.executeScript({code: `
var inputToFill = document.getElementById('register-email');
if (inputToFill) inputToFill.value = '${document.getElementById('email').value}';
`});
};
答案 1 :(得分:0)
页面的文档变量与弹出窗口中的变量不同。您需要在executeScript函数上传递输入的电子邮件值。
您需要使用弹出窗口的document变量获取输入值,然后将该代码插入页面。
popup.js
// make sure your popup was loaded
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('clickactivity').addEventListener('click', function () {
// if you pass tabId as null, it already gets the active tab from the current window
// assuming that register-email exists on the page that in you'll insert this script code
const emailFromPopup = document.getElementById('email').value
const code = 'document.getElementById("register-email").value =' + `'${emailFromPopup}'`
chrome.tabs.executeScript(null, { code });
})
})