I am using a WebBrowser
component in WPF to host some JavaScript + HTML and I want to be able to pass a customisable object in as the ObjectForScripting
property. My end goal is that the javascript running in the WebBrowser
can call something like:
window.external['lookup'].getValue(someId);
I can achieve something close to this by implementing a class with ComVisible
set to true
that has a lookup
property on it:
[ComVisible(true)]
public class ScriptingContext
{
public LookupService lookup { get; set; } //where LookupService is also ComVisible
}
However, I want to be flexible about the members on the ObjectForScripting
that I'm passing in so I can't specify what each property will be beforehand.
Ideally I would like to just specify a name-object pair to pass in, but afaict this doesn't work.
What I have tried (and failed with) so far:
Dictionary<string,object>
as my contextDictionary<string,object>
that is marked as ComVisible
ExpandoObject
List<KeyValuePair<string,object>>
List<KeyValuePair<string,object>>
that is marked as ComVisible
Is there some way to pass a customisable ObjectForScripting
into the WPF WebBrowser
that I am missing?
I'm not sure what you mean by customisable, but there's plenty of ways to accomplish what you're going for, such as building a wrapper for your dictionary and having that be your ObjectForScripting:
[ComVisible(true)]
public class ScriptingContext
{
private Dictionary<string, object> objectsForScripting;
public object GetValue(string s)
{
return objectsForScripting[s];
}
}
With the corresponding javascript window.external.GetValue("lookup").getValue(someId)
.
Note that you can also pass ComVisible objects to javascript through the InvokeScript method and interact with them that way, using something like webBrowser.InvokeScript("RegisterProperty", "lookup", lookupObject)
and manage the objects you're exposing on the javascript side.