简体   繁体   中英

Chrome Extension - Passing variables from HTML file to .js file

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();

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 .

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 });
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM