Problem with Js Lib

I Create file with extension “.jslib”:

var CookieLib = {
    GetCookies: function()
    {
        alert(document.cookie);
        return document.cookie;
    }
};

mergeInto(LibraryManager.library, CookieLib);

Then i add DLLImport and call method:

[DllImport("__Internal")]
    private static extern string GetCookies();

void Awake()
    {
        GetCookies();
    }

I Have exception:

What’s wrong? How i can fix it? In WebGL Alert from GetCookies working.
Sorry for my mistakes. English isn’t my native english…

Where did you place the jslib file?

Assets/Plugins/WebGL/filename.jslib
Example of documentation is also not working.

You can’t return document.cookie just like that, you should follow the manual blueprint:

StringReturnValueFunction: function()
{
var returnStr = "bla";
var buffer = _malloc(lengthBytesUTF8(returnStr) + 1);
writeStringToMemory(returnStr, buffer);
return buffer;
}

But I don’t think that solves the exception. I take it you have this exception in the browser, right? Because in the editor it would be normal of course.

I have this error in editor and browser.

As mentioned by alexvda, you will always get that exception in editor. JSLIB files only run in browser.

Since you’ve also stated that the alert does run, that means that your not actually having a missing method exception at all when in browser.

The issue is that you likely do not want to have your js lib return a string. below is how you would go about getting a string using string builder with p/invoke

var CookieLib = {
    GetCookies: function(buf)
    {
        alert(document.cookie);
        stringToUTF16(document.cookie, buf);
        return document.cookie.length;
    }
};

mergeInto(LibraryManager.library, CookieLib);
[DllImport("__Internal",CharSet = CharSet.Unicode)]
    private static extern int GetCookies([MarshalAs(UnmanagedType.LPWStr)]System.Text.StringBuilder buf);

void Awake()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder() { Capacity = 500, };// 500 char max..
        GetCookies(sb);
        string value = sb.ToString();
    }

see how that works (note that value, would be set to the string.) the marshalas attribute may or may not be required

One last note, when you build the player for webgl, since this call is in Awake, you’ll likely get the missing method exception while building which is (or should be) harmless. If you did want to avoid it though… you would place the following around awake

#if !UNITY_EDITOR && UNITY_WEBGL
void Awake { .......... }
#endif