3

I'm not sure this is supported but wanted to see if any of you had come up with something creative to work around this.

Is there a way to call javascript from silverlight, without having to define any javascript functions on the aspx page/external js?

I'd like to be able to do something like:

HtmlPage.Window.Invoke("(function () { window.lastErrorMessage = 'foo'; })();")

Which, to forgo conversations about style, I'd agree goes against many best practices rules, but my current purpose is brainstorm some quick-and-dirty error reporting (could you even call it reporting?) before we implement the existing database-centric error logging in this solution.

Any thoughts? The idea is to generate something discreet that a user wouldn't feel intruded upon or something too technical (like IE's script error dialog), but something our app support could get a little more info from without access to code bases etc.

Thanks, Matthew

2 Answers 2

4

The method you are looking for is Eval not Invoke:-

HtmlPage.Window.Eval("(function () { window.lastErrorMessage = 'foo'; })();")
Sign up to request clarification or add additional context in comments.

2 Comments

+1: I had a typo that meant I did not get Eval to work, hence the longer workaround. sigh :)
can i -1 on google for not bringing this to my attention earlier? :) That's exactly what i was looking for - googling "silverlight call javascript" always brings up invoke - thanks!
3

You could add your JavaScript dynamically to the hosting page DOM using HtmlPage.Document and then execute your added methods. Or are you trying not to modify the page at all?

            HtmlElement head = HtmlPage.Document.GetElementsByTagName("head")[0] as HtmlElement;
            HtmlDocument htmlDocument = HtmlPage.Document;
            HtmlElement scriptElement = htmlDocument.CreateElement("script");
            scriptElement.SetAttribute("type", @"text/javascript");
            scriptElement.SetProperty("text", "function testMe(p) { alert(p); }");
            head.AppendChild(scriptElement);
            // Invoke like this
            HtmlPage.Window.Invoke("testMe", "hello");

1 Comment

+1: this is still cool enough I may use it somewhere else. I use jQuery so much i forget that modifying the DOM is a normal part of web dev life.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.