Reputation: 538
I have a CEFSharp browser implementation where I have few C# objects binded to CEF browser using JavascriptObjectRepository
. Issue is when user tries to navigate across pages, he can end up on unintended page which can exploit this exposed object. I need to restrict these objects to specific domain(s). Is there a right way to achieve this?
Note: I've see MethodInterceptor that can be added in binding option, but it doesn't give out url as a parameter.
Upvotes: 1
Views: 509
Reputation: 538
Got stuck on this for a while but found the answer. I had to implement MethodInterceptor for tracking the object usage across sites. Since the method interceptor didn't have a URL parameter, I had to explicitly subscribe to address the change event in the ChromiumWebBrowser instance.
Binding -
BindingOptions bindingOptions = new BindingOptions();
bindingOptions.MethodInterceptor = new CefJSObjectInterceptor(browser);
browser.JavascriptObjectRepository.Register(jsName, jsObj, true, bindingOptions); // Note: skipped LegacyJavascriptBindingEnabled check
Method interceptor implementation -
internal class CefJSObjectInterceptor : IMethodInterceptor
{
string currentAddress;
public CefJSObjectInterceptor(ChromiumWebBrowser browser)
{
browser.AddressChanged += Browser_AddressChanged;
}
private void Browser_AddressChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
currentAddress = e.NewValue.ToString();
}
public object Intercept(Func<object[], object> method, object[] parameters, string methodName)
{
Uri uri = new Uri(currentAddress);
string url = uri.Host.ToString();
if (isAcceptableURL(url))
{
object result = method(parameters);
return result;
}
return null;
}
bool isAcceptableURL(string url)
{
HashSet<string> validURLs = new HashSet<string> { "google.com", "microsoft.com", "127.0.0.1" };
foreach (var validURL in validURLs)
{
if (url.EndsWith(validURL))
{
return true;
}
}
return false;
}
}
Upvotes: 1