1

I try to 'transfer' a variable from one js file to another.

I already tried to use import/export however it didn't work.

test1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="wrapper">
        <h1 class="sentence">hey guys</h1>
    </div>
    <script src="test1.js" type="module"></script>
</body>
</html>

test1.js

let greeting=document.querySelector('.sentence').innerHTML;
console.log(greeting);

test2.js

$.getScript('test1.js',function(){
    console.log(greeting);
}) 

the error messages i get are: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///Users/michalislazaris/Desktop/test.js. (Reason: CORS request not http). and: Module source URI is not allowed in this document: “file:///Users/michalislazaris/Desktop/test.js”.

5
  • 1
    Because you're running them on your local file system. They should be fine on a website/web server. Commented Aug 12, 2019 at 8:27
  • 1
    Your error message talks about test.js but you've said your files are test1.js and test2.js, so does test.js even exist? Commented Aug 12, 2019 at 8:30
  • Also duplicate of stackoverflow.com/questions/8348401/… and many others. Maybe check out stackoverflow.com/help/how-to-ask :) Commented Aug 12, 2019 at 8:35
  • Possible duplicate of JavaScript: Two separate scripts - share variables? Commented Aug 12, 2019 at 9:23
  • @MattEllen i just changed test.js to test1.js in stackoverflow in order to make it clear. The real file is named test.js Commented Aug 12, 2019 at 10:03

1 Answer 1

1

Judging from the error messages generated you're running your application locally. This results in the blocked CROSS-Origin Request since both pages aren't located on the same "server".

In order to solve this, you have to run your application on a development server and there are tons of options to pick from! My personal favorite is Parcel, which is pretty straight forward (minimal config) to use.

Once your app is running on a server the error must disappear.

Sign up to request clarification or add additional context in comments.

1 Comment

ty <3 i will try it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.