I'm working on a program that will be used by different users and they will individually change the content of the js file to match with their expectation.
On the web I found many tutorials on how to call JS function in unity WEBGL but the Js file was built with the unity project.
I wanted a way to call a JS function which is hosted by the website (incluing it in the index.html of unity WEBGL but without building it).
What you are trying to do is possible. But it is a bit of a hack.
a quick google search turned up this article, from the unity documentation But it might not be clear how to do it. so here is an example:
Let us say you want to call a js function called foo().
The first thing to do is create a file with a .jslib file extension in a folder named "Plugins". this file tells unity that the function exists and is a just js
mergeInto(LibraryManager.library, {
foo_js: function () {
foo()
},
});
Here I declare a function called foo_js and tell unity that it exists.
This function consists of js, and in this case, all it does is call the js function foo().
Note: the name foo_js is arbitrary, and it can be called anything, Including just foo. but it is the same name as you will be using in c#. so I would recommend making it clear that it is not a native c# function
now in a c# script, you start by declaring the function, which is done by adding
[DllImport("__Internal")]
private static extern void foo_js();
to a class and add
using System.Runtime.InteropServices;
to the top of the file
you can now call the function as foo_js() in your c# script
after you have built the unity project, you need to add a js script. To "index.html" that has a function called foo() for unity to call.
And it should work, for more detail read the article from the beginning.
Something I forgot to mention is that it is not going to work in the editor, as the js function is not defined, so you need to export the project and define the function on the website it should be possible to detect that the game is running in the editor and use a default behaviour instead of the js function, but I am not sure how right now