I’m using libsodium library for encryption in browser extensions (chrome and safari) for encrypting data retrieved from webpages. I’m also using it in iOS wkWebView browser which works fine for most of the web apps.
All I had to do was grab the sodium.js file from https://github.com/jedisct1/libsodium.js/tree/master/dist/browsers/combined
Add it to the project and start using it (not going into the details of how js file is injected into webview or extensions).
e.g.
sodium.crypto_secretbox_easy(msg, nonce, key)
This works fine for extensions and mostly on iOS as well. But for some of the web apps on iOS webview, started running into the following problem :
The export ‘sodium’ was not defined. On further debugging into the sodium.js code found that the failure is because sodium code checks if the function ‘define’ is present and if so calls into that function with its own ‘factory’ parameter. Check code snippet from sodium.js :
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports === 'object' &&
typeof exports.nodeName !== 'string') {
factory(exports);
} else {
factory(root.libsodium = {});
}
This is the case which fails to initialize ‘sodium’ export.
Looks like the function ‘define’ is part of JQuery which is likely defined by the active web app in webview.
A success scenario would be that ‘define’ is not present and it directly calls into the ‘factory’ function at the end, which initializes the ’sodium’ export properly.
To summarize it appears : Libsodium library looks for JQuery / AMD definitions before intializing its code. And if it finds it calls into the JQuery ‘define’ to initialize its code. Somehow relying on existence of JQuery does not go well.
Guess the first question which pops up :
- Can we have libsodium not rely on JQuery (even if it exist). (didn’t find anything).
Found some documentation on libsodium about using libsodium wrapper if AMD import is present. As below :
var sodium = require('libsodium-wrappers’);
This was no good. This caused exception : that the library or its dependency could not be loaded.
Any suggestions/pointers would be welcome to get this to work. Thanks.