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

痴心易碎 提交于 2019-12-20 05:58:15

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/54727191/chrome-extension-passing-variables-from-html-file-to-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!