How to invoke javascript in WebView Windows 10 UWP? - javascript

I am trying to load a javascript in WebView to do some calculations and get the output in a string. I tried to use following code
string htmlFragment = "<html><head><script type='text/javascript'>" +
"function doubleIt(incoming){ " +
" var intIncoming = parseInt(incoming, 10);" +
" var doubled = intIncoming * 2;" +
" document.body.style.fontSize= doubled.toString() + 'px';" +
" return doubled.toString());" +
"};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
htmlView.NavigateToString(htmlFragment);
htmlView.LoadCompleted += async(s1,e1) =>
{
string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" });
Debug.WriteLine(result);
};
Update
I am able to load simple javascript easily now based on help provided in the answer. But now I am facing issues when there is more than one function in javascript, I am getting an exception. I am trying the following code
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return 10;};" +
"function b(){return 20;};" +
"function c(){return 30;};" +
"return (a()*b()*c());" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
Please suggest.

The documentation for this feature is really poor. It took me some time to figure out how to invoke Javascript in UWP WebView
When you first look at the function call webView.InvokeScriptAsync(string,string[]) your initial reaction is that they want the function name as the first parameter and then the function paramaeters as the string array. (mainly because the MSDN documentation says this)
Parameters
scriptName
Type: System.String [.NET] | Platform::String [C++]
The name of the script function to invoke.
arguments
Type: System.String[]
[.NET] | Platform::Array [C++]
A string array that
packages arguments to the script function.
HOWEVER, this is wrong and will lead to hours of head banging. REALLY, what they want is the word "eval" in the first parameter and then a string array of functions, and or commands you wish to eval
var value = await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
Having worked with Microsoft APIs for a few years now I am convinced that this is not the intended way of consuming this function and is a bit of a hack. Unfortunately if you want to consume JavaScript this is the only way that I know that works currently.

Anthony,
Try to check your own suggestion:
await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
or:
await webViewer.InvokeScriptAsync(functionName, new string[]{ functionParameters });
The same as Microsoft suggests, just you are limiting a function name by one ("eval") - not necessary. Trust me, you can use any function name, as I am now with UWP and before with windows phone hybrid apps.

The question is already 4 years old, but I'm coming to see why you were getting an empty string as a result.
In your example, the functions in JavaScript return integers while the expected value is of type string.
By modifying these functions and returning a string like this:
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return '10';};" +
"function b(){return '20';};" +
"function c(){return '30';};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
We get the good result on the way back.

Related

LineBreak in console object

Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test

Send an array of objects from JS/TS (Angular 2) to WCF?

i have to send an array of objects like this
[{"Cod":"1"},{"Cod":"5"}]
to my C# WCF Service which i used until today without problems with wsHttpBinding (so no JSON using here, only XML).
The request, POST, contains this param:
let param = "<cod>" + data + "</cod>";
My problem is on WCF because i can't find a way to get that array of objects from the parameter of the method:
public string GetArrayOfObjects(CompositeType[] cod)
{//implementation not important because i can't enter here...}
where CompositeType is:
[DataContract]
public class CompositeType
{
string cod;
[DataMember]
public string Cod
{
get { return cod; }
set { cod = value; }
}
}
I have tried so many things like changing the parameter to:
Object[] cod
List<string> cod
...
Everytime i get this error (translating):
Exception generated by the formatter in an attempt to deserialize the message: Error trying to deserialize the parameter http://tempuri.org/:cod. InnerException: 'Error at line 1 position 341. Expected status 'Element' .. Found 'Text' with '' name space ''. '.
...
This is the post message that i'm sending:
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<s:Envelope xmlns:a=\"http://www.w3.org/2005/08/addressing\" xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\">" +
"<s:Header>" +
"<a:Action s:mustUnderstand=\"1\">http://tempuri.org/IService1/" + GetArrayOfObjects + "</a:Action>" +
"</s:Header>" +
"<s:Body>" +
"<" + GetArrayOfObjects + " xmlns=\"http://tempuri.org/\">" +
param +
"</" + GetArrayOfObjects + ">" +
"</s:Body>" +
"</s:Envelope>";
where param is defined before. The JSON.stringify of data inside param gives the first example of this question ([{"Cod":"1"},{"Cod":"5"}]). This post message was always fine with single value params.
Some sites show a solution with a json deserializer on wcf, but i'm using XML...it's not an option right now to re-implement the project in json.
I tried for one day but i didn't find a solution, i'd love to hear some solutions from you! Thanks to all.

could not able to pass string values to javascript function

When trying to pass String value to the javascript function , Uncaught ReferenceError is thrown on the browser console.
Below is the sample code:
function mySampleTest(myId, comments){
alert("myId " + myId);
alert("comments : " + comments);
}
var myTest = function(value, rowIndex) {
var myId = this.grid.getItem(rowIndex).MY_ID;
var comments = this.grid.getItem(rowIndex).COMMENTS;
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , "+comments+")\">";
};
The JavaScript function mySampleTest is being called when the user clicks the image but it throws a JavaScript error when I pass the string comments to mySampleTest function. If I remove the comment parameters and just pass the myId to mySampleTest(..), it works fine.
Please suggest how to pass string values to the JavaScript function.
I tried the below also, but didn't work.
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , \'' + comments + '\')\">";
As a professor once told me, much of writing code involves "being the computer".
Consider your function's output for a moment and you should see the issue pretty quickly:
<img src=whatever/your/context/path/is/images/image1.gif
width="25" height="25"
onClick="mySampleTest(12345, this is a comment)">
Your javascript is invalid:
mySampleTest(12345, this is a comment)
It should be:
mySampleTest(12345, 'this is a comment') // <--- notice the quotes
Which would translate all the way back to:
return "<img src=\"<%=request.getContextPath()%>/images/image1.gif\" width=\"25\" height=\"25\" onClick=\"mySampleTest('"+ myId +"' , '"+comments+"')\">";
Not to mention your src attribute really needs quotes.

Javascript - concat string does not work as expected

What's the wrong with this Javascript line?
user: h.reem
domain: somedomain
var target = "//account/win/winlogin.aspx" +
"?username=" +
user.toString() +
"&domain=" +
domain.toString();
the resutl is always:
//account/win/winlogin.aspx?username=h.reem
Any idea!!
alert(user + "X") shows only h.reem
The ActiveX component is probably returning a null terminated string (I've seen this with Scripting.TypeLib & a couple of the AD objects for example) so concatenating it with another string fails. (You can verify this if 0 === user.charCodeAt(user.length - 1)).
You will need remove the last character before using the string;
user = user.substr(0, user.length - 1);
try:
var sUser = user.toString();
var sDomain = domain.toString();
var target = "//account/win/winlogin.aspx" + "?username=" + sUser + "&domain=" + sDomain;
The above might not fix your problem but it should expose it - Could be that your user.toString() method isn't returning a string and is short-circuiting things... If this doesn't answer your question I'd be glad to assist further, but it would be helpful if you posted the implementation or source of "user" somewhere ...

searching equivalent function/way to "list()" from php

i'm searching for an equivalent function for php's "list()". i'd like to split a string with "split()" and put the array values in two different variables. hopefully there's another way to do this as short and performance-optimized as it could be.
thanks for your attention!
Here's a list implementation in javascript:
http://solutoire.com/2007/10/29/javascript-left-hand-assignment/
Maybe PHP.JS is worth looking at (for future stuff maybe). I noticed that the list() was only experimental though but maybe it works.
If you can live without the naming, you can do this:
var foo = ["coffee", "brown", "caffeine"];
foo[0] + " is " + foo[1] + " and " + foo[2] + " makes it special";
Alternatively, use a object to name the keys:
var foo = {drink: "coffee", color: "brown", power: "caffeine"};
foo.drink + " is " + foo.color + " and " + foo.power + " makes it special";
I think the closest you can get is the explicit
var args = inputString.split(",");
// Error checking, may not be necessary
if (args.length < 3)
{
throw new Error("Not enough arguments supplied in comma-separated input string");
}
var drink = args[0];
var color = args[1];
var power = args[2];
since Javascript doesn't have multiple assigment operators. I wouldn't worry too much about the efficiency of this; I expect that the list function in PHP basically boils down to the same thing as above, and is just syntactic sugar. In any case, unless you're assigning hundreds of thousands of variables, the time to execute anything like the above is likely to be negligible.

Categories