Reputation: 67
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
<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();
Upvotes: 0
Views: 651
Reputation: 5118
Your content script and your popup script run on different documents: you cannot access a variable of one of them from the other directly.
Try with this:
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.
Upvotes: 1
Reputation: 967
The document variable of the page is not the same as the one from the popup. You need to pass the input email value on the executeScript function.
Your need to get the input value using the document variable of your popup window, then inject that code on the page.
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 });
})
})
Upvotes: 0