- Home /
WebGL build .jspre javascript plugin - how do I call functions from page?
I have a Unity WebGL project in which I would like to expose some Javascript functions to the webpage.
This thread seems to suggest that any javascript in a .jspre file is "...appended to the beginning of the JavaScript framework without any preprocessing" - I assumed that this meant that I could simply call this code from the containing page, but that doesn't appear to be the case (I cannot find where my code lives in the deployed webpage). The functions are definitely included in the build because I can access them with the 'compiled' javascript code in the .jslib file.
What do I have to do to access the functions defined in my .jspre file, from the containing page?
Turns out we can add functions to 'gameInstance' and/or 'gameInstance.$$anonymous$$odule' by adding the following to the .jspre file;
$$anonymous$$odule.myFunction = function() {
console.log("$$anonymous$$odule.myFunction called");
}
gameInstance.myFunction = function() {
console.log("gameInstance.myfunction called");
}
I have no idea if this is recommended or not. It does appear that the only method of communicating Javascript->Unity C# is via the Send$$anonymous$$essage mechanism (e.g. no javascript callback functions, etc)
Answer by De-Panther · Jul 04, 2020 at 06:03 PM
It's been a few years, but it's one of the first results in Google when looking for "jspre". So as written in the thread you mentioned, it'll go into the "*.framework.unityweb" file. More precisely into the Module object. If you want to be able to call a method of your ".jspre" file from the web page, you can add it to the Module object. Something like:
Module['yourMethod'] = function () {
console.log('someone called my method');
}
and use it in the page like that:
unityInstance.Module.yourMethod();