Opening a Silverlight Window From Javascript and passing an object - c#

I am looking for a way to open my silverlight application from my web application using javascript. I will also need to pass a string to the silverlight application during this process. The code below will currently open the silverlight application for me. I need to know how to do this while passing in the string value to silverlight.
$(function () {
$('.cell').on('focus', 'textarea', function () {
var inputValue = $(this).val();
window.open('/TestPage.aspx');
});
});
Note: I have searched everywhere for the answer to this and cant seem to find a decent solution. All of the demos I've found are incomplete or do not function as expected.

You could pass it in the query string:
window.open('/TestPage.aspx?input=' + inputValue);
Retrieve it in Silverlight using HtmlDocument.QueryString:
string inputValue = null;
if (HtmlDocument.QueryString.ContainsKey("input"))
inputValue = HtmlDocument.QueryString["input"];

Related

C# BHO return value from Javascript

I have a C# BHO which calls some JS functions in a document. Normally I did it like this (and everything worked fine):
IHTMLWindow2 wnd;
//...
wnd.execScript("testMethod(\"testData\");");
But now I need to return value from JS method to my BHO. I implemented test JS method which returns a string but when I use execScript nothing is returned. I started to read documentation about execScript method and found that now they recommend to use eval instead.
But I can't find any information on how to call this from my C# BHO. I have found this question and there is even c# example but it assumes that I host WebBrowser control and suggests to use Document.InvokeScript. And in MSHTML none of IHTMLDocument* interfaces have InvokeScript method. Am I missing something?
EDIT 1: Here is a question which kind of answers how to get return value from execScript. But its probably not smart to use execScript if MSDN says it is no longer supported.
EDIT 2:
More code for this issue. First of all I have a JS function like this (in a file called func.js):
getElemHtml = function () {
var myElem = document.getElementsByClassName("lineDiv")[0];
// A lot more code goes here...
alert(myElem.innerHTML);
return myElem.innerHTML;
}
Then in my BHO I inject this script into the page like this:
StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("func.js"));
string scriptContent = reader.ReadToEnd();
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)ihtmlDoc2.all.tags("head")).item(null, 0);
IHTMLScriptElement scriptObject = (IHTMLScriptElement)htmlDoc2.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = scriptContent;
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
Then in another part of BHO I want to get return value from getElemHtml():
var retVal = ihtmlWindow2.execScript("getElemHtml();");
but retVal is null. I see that script is executed and I see that return value is not null because I see alert window with return value. What I want is a return value from this JS function in my C# BHO code. It looks like this can be done using this answer but as I have said MSDN says I should use eval instead of execScript. The question is how to call eval and get a return value from my JS function.
I have found some links which allow to get return value from JS in C++ BHOs but I haven't managed to convert them in C# so here is a workaround way which worked for me:
// Execute method and save return value to a new document property.
ieHtmlWindow2.execScript("document.NewPropForResponse = getElemHtml();");
// Read document property.
var property = ((IExpando)ieHtmlDocument2).GetProperty("NewPropForResponse", BindingFlags.Default);
if (property != null)
return property.GetValue(ieHtmlDocument2, null); // returns return value from getElemHtml.

Using Javascript for Google Maps API from WPF

I am creating an application that interfaces with Google's Maps API v3. My current approach is using a WebBrowser control by WebBrowser.Navigate("Map.html"). This is working correctly at the moment; however, I am also aware of WebBrowser.InvokeScript(). I have seen this used to execute a javascript function, but I would like to have something like the following structure:
APICalls.js - Contains different functions that can be called, or even separated out into a file for each function if necessary.
MapInterface.cs
WebBrowser.InvokeScript("APICalls.js", args) - Or control the javascript variables directly.
I have seen the InvokeScript method used, but none of the examples gave any detail to the source of the function, so I'm not sure if it was calling it from an html file or js file. Is it possible to have a structure like this, or a similarly organized structure, rather than creating an html file with javascript in each one and using Navigate()?
Additionally, are there any easier ways to use Google Maps with WPF. I checked around, but all of the resources I found were at least 2-3 years old, which I believe is older than the newest version of the maps API.
I can't suggest a better way of using Google Maps API with WPF (although I'm sure it exists), but I can try to answer the rest of the question.
First, make sure to enable FEATURE_BROWSER_EMULATION for your WebBrowser app, so Google Maps API recognizes is it as modern HTML5-capable browser.
Then, navigate to your "Map.html" page and let it finish loading. Here's how it can be done using async/await (the code is for the WinForms version of WebBrowser control, but the concept remains the same).
You can have your APICalls.js as a separate local file, but you'd need to create and populate a <script> element for it from C#. You do it once for the session.
Example:
var scriptText = File.ReadAllText("APICalls.js");
dynamic htmlDocument = webBrowser.Document;
var script = htmlDocument.createElement("script");
script.type = "text/javascript";
script.appendChild(htmlDocument.createTextNode(scriptText));
htmlDocument.body.appendChild(script);
Then you can call functions from this script in a few different ways.
For example, your JavaScript entry point function in APICalls.js may look like this:
(function() {
window.callMeFromCsharp = function(arg1, arg2) {
window.alert(arg1 + ", " +arg2);
}
})();
Which you could call from C# like this:
webBrowser.InvokeScript("callMeFromCsharp", "Hello", "World!");
[UPDATE] If you're looking for a bit more modular or object-oriented approach, you can utilize the dynamic feature of C#. Example:
JavaScript:
(function() {
window.apiObject = function() {
return {
property: "I'm a property",
Method1: function(arg) { alert("I'm method 1, " + arg); },
Method2: function() { return "I'm method 2"; }
};
}
})();
C#:
dynamic apiObject = webBrowser.InvokeScript("apiObject");
string property = apiObject.property;
MessageBox.Show(property);
apiObject.Method1("Hello!");
MessageBox.Show(apiObject.Method2());

dynamically evaluating javascript expressions in winrt/xaml/c# applications

Is there a way of evaluating javascript expressions, which are loaded from an external source at runtime, in a winrt application written in XAML and c#?
Consider the following pseudo-code:
String expression = File.ReadAll(somefile);
String result = AnyJavascriptEngineAvailableUnderWinRT.Evaluate(expression);
before winrt, we have been using Microsoft.JScript engine.
Now, with winrt, we have been trying Jint, which led to runtime exception "The API 'System.Type.ReflectionOnlyGetType(System.String, Boolean, Boolean)' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information."
To be honest, I would prefer addressing the built-in javascript engine coming with winrt, but I would also accept "AnyJavascriptEngineAvailableUnderWinRT", if it allows expressions to be evaluated dynamically.
You can do this easily by tapping into IE directly through the WebView.
Like this:
var js = "whatever you want";
var webView = new WebView();
var result = webView.InvokeScript("eval", new[] { js });
Best of luck!

IE 9 BHO addon. Error SCRIPT1014 with loading external JS-file

I'm trying to create simple Internet Explorer 9 addon using .Net and BHO to load external js-file on page and execute it.
I created ieInstance_DownloadComplete (I also tried ieInstance_DocumentComplete, but things were worse) event handler:
InternetExplorer explorer = this.ieInstance;
var document = explorer.Document as IHTMLDocument2;
document.parentWindow.execScript(
#"
if (document.getElementById('KCScript') == null)
{
var fileref=document.createElement('script');
fileref.setAttribute('id', 'KCScript');
fileref.setAttribute('type','text/javascript');
fileref.setAttribute('charset', 'UTF-8')
fileref.setAttribute('src', 'C:/test.js');
fileref.onload = function () { eee(); };
if (typeof fileref!='undefined')
document.getElementsByTagName('head')[0].appendChild(fileref);}","JavaScript");
}
When page is loaded I can see my test.js attached to page in IE Developer Tools. But function eee() does not raise and i have an error:
"SCRIPT1014: Invalid character
test.js, line 1, character 1"
test.js:
function eee()
{
alert('ttt!');
};
test.js is UTF-8, so there is no reading problem.. there is something else
What's wrong? Any ideas?
Thanks in advance!
Try to resave JS in "UTF-8 without BOM" encoding
Try to place JS to remote server as http://example.com/test.js

Parse JavaScript code in C#

I have the following JavaScript code as a string literal:
var $Page = new function()
{
var _url= 'http://www.some.url.com';
this.Download = function()
{
window.location = _url;
}
}
Is there a way I could get the value of the _url variable from my C# code? An open source library perhaps? I did this using a Regular Expression, but I was hoping for a more elegant way.
You should take a look at the open-source Javascript .NET (http://javascriptdotnet.codeplex.com/) on Codeplex.
This sample of code should help you:
Javascript context = new JavascriptContext();
context.Run("var _url= 'http://www.some.url.com';") // You put your javascript in the function run
String url = (String)context.GetParameter("_url"); // You get your url from javascript
That's it.
There is an open-source JavaScript interpreter in C# at http://jint.codeplex.com, if you need more than just getting the value.
This is now moved to GITHUB
You could execute the javascript function using the DLR and/or MyJScript.
You could use a javascript parser, but parsing javascript for just that one value is probably way overkill.

Categories

Resources