AGupta
AGupta

Reputation: 5734

Sharing variable within different javascript file at client side

I was actually going through this link. which explains how we can share global variable across multiple js. but the point is what need to be done if I am getting some variable into one js and need to pass to another one mentioned in same document after the 1st one.
approach which followed was:
Script 1 <script type="text/javascript" src="js/client.js"></script>
body added some hidden input with id myHiddenId, where values are set using client.js
Script 2 <script type="text/javascript" src="js/anotherJS.js"></script>
inside script 2 I am simply using $("#myHiddenId").val(); and using for my purpose.

I want to know whether I am following correct approach, because that hidden field may have some data which client should not get aware of. is there any other way through which I can pass the variable values across the js files ? Since I am at beginner level hence digging up some resources/books but still no luck.

Upvotes: 0

Views: 441

Answers (1)

forsvunnet
forsvunnet

Reputation: 1258

If the client should not be aware of the data then you should not be using client side JavaScript. Any JavaScript executed in the browser can be debugged and viewed by the user.

You should always handle sensitive data on the server side.

Saving the variable in the JavaScript file or in the hidden element makes little difference.

Regarding using variables across files then you should be able to use any variables declared in Script 1 in Script 2 provided they are declared in the root scope and that Script 1 appears before Script 2 in the DOM.

<script> // Script 1
    var root_scope = 'This variable is declared at root';
    function some_function() {
        // Variables not defined at root are subject to the scope they are in
        var non_root = 'This is not at root';
    }
</script>

<script> // Script 2
    // Use the variable declared in Script 1:
    alert(root_scope); // This variable is declared at root
    // Note: declaring at root is the same as assigning to window
    alert(window.root_scope); // This variable is declared at root
    alert(typeof non_root); // undefined
</script>

Upvotes: 1

Related Questions