简体   繁体   English

从 silverlight 调用/生成动态 javascript

[英]Call/generate dynamic javascript from silverlight

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?有没有办法从 silverlight 调用 javascript,不必在 aspx 页面/外部 js 上定义任何 javascript 函数?

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.我们的想法是生成一些谨慎的东西,用户不会觉得被打扰或过于技术性的东西(如 IE 的脚本错误对话框),但我们的应用程序支持可以从不访问代码库等的情况下获得更多信息。

Thanks, Matthew谢谢,马修

The method you are looking for is Eval not Invoke :-您正在寻找的方法是Eval not Invoke :-

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

You could add your JavaScript dynamically to the hosting page DOM using HtmlPage.Document and then execute your added methods.您可以使用 HtmlPage.Document 将 JavaScript 动态添加到托管页面 DOM,然后执行您添加的方法。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM