0

Just started learning JS, and been having an issue with a library i'm trying to import.

The developer recommends the following:

<script>
    window.sodium = {
        onload: function (sodium) {
            let h = sodium.crypto_generichash(64, sodium.from_string('test'));
            console.log(sodium.to_hex(h));
        }
    };
</script>
<script src="sodium.js" async></script>

However, this only executes when the page loads - I can't run the functions further down the page when they are required. As such:

<script>
var App = new function(myLibrary){

    this.sodium = myLibrary;

    this.example = function () {
        h = this.sodium.crypto_generichash(64, this.sodium.from_string('test'));
        return this.sodium.to_hex(h);
    }

}

var create = new App(window.sodium);
</script>

/...../

<script>console.log(create.example());</script>


<script src="sodium.js" async></script>

How would I do this? I kept getting errors such as "sodium.crypto_generichash" is not a function. Or sodium is not defined.

jgLaus
  • 1

1 Answers1

0

This code is running before the library is loaded:

<script>
var App = new function(myLibrary){

this.sodium = myLibrary;

this.example = function () {
    h = this.sodium.crypto_generichash(64, 
    this.sodium.from_string('test'));
    return this.sodium.to_hex(h);
  }

}

Try removing the async and change the order of the scripts.

And run your code inside a window.onload function:

window.onload = function() {
    //your code
}
Mass C
  • 41
  • 4
  • I get "this.sodium.crypto_generichash is not a function" but within this.example if I console.log(window.sodium OR this.sodium), I can see all the functions are there? – jgLaus Mar 09 '18 at 16:17
  • Still getting the same "is not a function" issue, here's my current code for reference: https://jsbin.com/muxawegiji/edit?html,js,output – jgLaus Mar 09 '18 at 17:29
  • I think that sodium.js src url doesn't work as expected, because in the code you share on jsbin is undefined. – Mass C Mar 09 '18 at 19:49
  • Yes you are right, you can find it here if you like to download it: https://github.com/jedisct1/libsodium.js/tree/master/dist/browsers I still can't seem to call functions that are defined in the window.onload – jgLaus Mar 09 '18 at 19:56