简体   繁体   中英

Silverlight 4 MVVM: Call Javascript function from viewmodel

we have developed an Intranet Management Application with Silverlight 4. We have been asked to add the functionality to call a remote desktop tool which is installed on clients using the Intranet SL App. In an earlier version of the tool written in ASP.NET we just added a Javascript function to the aspx page like this:

function RunShellCommand()
 {
        var launcher = new ActiveXObject("WScript.Shell");
        launcher.Run("mstsc.exe");
    }

and called it from ASP.NET.

Now it's clear that SL4 is running in a sandbox and that I cant use the AutomationFactory to create a WScript.Shell object (out of browser mode is not an option).

I thought I could circle around the problem by, again, adding the RunShellCommand javascript method in the aspx page where the SL4 control is hosted and call it via

HtmlPage.RegisterScriptableObject("Page", this);

HtmlPage.Window.Invoke("RunShellCommand", "dummydata");

from my ViewModel. When I run the Application the debugger just skips the RegisterScriptableObject method and quits. Nothing happens. My question is if am doing something wrong or if this just wont work this way. Is it possible that I cant do a RegisterScriptableObject from a viewmodel?

EDIT: When I explicitly put a try, catch block around the two methods I get an ArgumentException from the first method stating that the current instance has no scriptable members. When I delete the first method and only run the Invoke, I get a browser error stating that the automation server cant create the object. So is there really no way (except OOB mode) to do this?

Yes, the explanation is correct: you should add at least one method with the ScriptableMember attribute in order that you can use the RegisterScriptableObject method. But it is used only for calling C#-methods from JavaScript.

As far as I see, you want to do the opposite: to call JavaScript code from the Silverlight application. Then you need only one line:

HtmlPage.Window.Invoke("RunShellCommand");

The error automation server cant create the object has nothing to do with Silverlight. I'm sure that if you call the JS function directly - the error will remain. According to the internet, the reason might be not installed Microsoft Windows Script . Or it is because of security restrictions of the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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