简体   繁体   中英

use variable from js file into another js file

I am doing an autofill extension for chrome. I made the html file where user put his information and i want that these information will be saved, because i need to use that information as a variable from a js file. This is the html popup:

<html>
  <head></head>
  <body>
    <div class="simple-form">
      <form method="post">
        <input type="text" name="fname" id="full_name" placeholder="Write here your full name"><br><br>
        <input type="email" name="email" id="email" placeholder="Write here your email"><br><br>
        <input id="save" type="button" value="Salva">
      </form>
    </div>
    <script type="text/javascript" src="scriptExport.js"></script>
  </body>
</html>

and this is the js file:

const button = document.getElementById('save');

button.addEventListener('click', updateButton);

function updateButton() {
  if (button.value === 'Save') {
    button.value = 'Done';
    var full_name_E = document.getElementById('full_name').value;
    var email_E = document.getElementById('email').value;
}
  else {
    button.value = 'Save';
  }
}

I need to load full_name_E and email_E in another js file that is the autofiller. I tried with import and export but it doesn't work.

Your problem is, that full_name_E and email_E are only available in the local scope of the function updateButton . To make the available at the global scope, initialize them at the top of your code:

const button = document.getElementById('save');
var full_name_E;
var email_E;

button.addEventListener('click', updateButton);

function updateButton() {
  if (button.value === 'Save') {
    button.value = 'Done';
    full_name_E = document.getElementById('full_name').value;
    email_E = document.getElementById('email').value;
}
  else {
    button.value = 'Save';
  }
}

If you want to learn more about this topic:

Also you can pass these variable in a function which you can define in your other js file.

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