Search code examples
javascriptwebviewwindows-store-appsinvokescript

Return an existing javascript variable from a WebView via InvokeScriptAsync


Ok, this is silly. I have an existing variable in the HTML I load into my WebView, called caret_position

I want to retrieve it via InvokeScriptAsync in my Windows Store app. Here's what I've tried.

return await HtmlEditor.InvokeScriptAsync("eval", 
    new string[] { "return caret_position;" });

return await HtmlEditor.InvokeScriptAsync("eval", 
    new string[] { "caret_position;" });

Neither of these work. The only way I can get it to work is to write it to a hidden input in javascript and then use this call.

return await HtmlEditor.InvokeScriptAsync("eval", 
    new string[] { "document.getElementById('this_is_silly').value;" });

Is there a way I can just access the javascript variable directly or do I have to jump through these hoops every time?


Solution

  • InvokeScriptAsync works only with string return values; if caret_position is a number, then it will cause trouble in the conversion. That is, a function {return caret_position; } would be returning a number when eval'd. So you need to make sure that function is returning a string, e.g. return caret_position.toString();