Closing a webpage running in a WPF WebBrowser - javascript

First a bit of background
I'm working on a Web application, that will be running within a WebBrowser, within a WPF application.
This is a temporary necessity while we're gradually moving functionality to the web app. As long as that's not finished, the WPF client is still needed. Ultimately the WPF client will phase out completely.
Now to the issue at hand
When the user closes the client (webpage), the webbrowser should catch that event and also close the window it is a child to.
I found this link describing what I would need: WebBrowser and javascript window.close()
Alas, I don't think the answer described there would still work, as it's not possible to even do a window.close(), because I'm not the one opening the window I'm running on. Browsers have (rightfully) tightened their security since then.
The question
Is there a way to trigger a Window close from the client, that bubbles up to the WPF?
Thanks.

I have used a WebBrowser control to call methods in a WPF application from the JavaScript before using WebBrowser.InvokeScript and WebBrowser.ObjectForScripting
See this MSDN article How to: Implement Two-Way Communication Between DHTML Code and Client Application Code
Also see this CodeProject article which looks like it might solve your problem
Call a C# Method From JavaScript Hosted in a WebBrowser
[ComVisible(true)]
public class ScriptManager
{
// Variable to store the form of type Form1.
private Window _window;
// Constructor.
public ScriptManager(Window window)
{
// Save the form so it can be referenced later.
_window = window;
}
// This method can be called from JavaScript.
public void MethodToCallFromScript()
{
// Call a method on the form.
_window.Close();
}
}
from code behind of Window:
webBrowser1.ObjectForScripting = new ScriptManager(this);

That worked, thanks!
I did the following:
[ComVisible(true)]
public class ScriptManager
{
protected Window Window { get; set; }
public ScriptManager(Window window)
{
this.Window = window;
}
public void CloseWindow()
{
this.Window.Close();
}
}
And in my Window (Loaded Event):
// Build browser
this.Browser = new WebBrowser();
this.Browser.Navigate(this.GetUri());
this.Browser.ObjectForScripting = new ScriptManager(this);
The client Javascript then does:
$scope.Close = function() {
window.external.CloseWindow();
}

Related

Catch certain Javascript function calls in a WebView

I am writing a basic web browser that can only go to a certain website (developed and maintained by another company) for my work, however in order for the log in and the time spent on the site to be counted (two VERY important things for my company) you need to log out with a certain button on the site.
I looked at the page source and all that button does is call a javascript function (named something like doLogoff() or something similar) which on a normal browser simply closes the window that is created after you log in.
In my application everything is done in ONE window, there are no tabs (there are no need for them) and I'm not entirely sure what the call to close the window does to my application, but the site on the WebView simply stays on that page and only goes back to the login page if you click on a link.
Is there anyway to detect when a certain JavaScript function is called in a WebView? If I can bind that function and make sure the log out is actually being performed, then I can just make the webview go to the login page myself.
You can do that with a JavascriptInterface. The following example comes from the documentation. It works the other way round. You can create a function in javascript that will trigger java code in your activity.
You declare your interface in your java code.
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
You add the interface to your WebView
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
And in your web page you can call the java method from a script
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
First, create the JavascriptInterface, prescribed by NathanZ.
Then override the function that you want to hook into, like this:
webview.loadUrl("javascript:" +
"var functionNameOriginal = functionName;" +
"functionName = function(args) {" +
"Android.showToast();" +
"functionNameOriginal(args);" +
"}");

WebView hides soft keyboard during loadUrl(), which means a keyboard cannot stay open while calling javascript

Since the way you call javascript on a WebView is through loadUrl("javascript: ... "); The keyboard cannot stay open.
The loadUrl() method calls loadUrlImpl() , which calls a method called clearHelpers() which then calls clearTextEntry(), which then calls hideSoftKeyboard() and then we become oh so lonely as the keyboard goes away.
As far as I can see all of those are private and cannot be overridden.
Has anyone found a workaround for this? Is there a way to force the keyboard to stay open or to call the javascript directly without going through loadUrl()?
Is there anyway to override the WebView in a way to prevent (the private method) clearTextEntry() from being called?
Update
KitKat added a public method for invoking javascript directly: evaluateJavascript()
For older apis, you could try a solution like below, but if I had to do this again I'd look at just building an compatibility method that on KitKat uses the above method and on older devices, uses reflection to drill down to a inner private method: BrowserFrame.stringByEvaluatingJavaScriptFromString()
Then you could call javascript directly without having to deal with loadUrl and adding "javascript: " to the script.
Old Answer
As requested by Alok Kulkarni, I'll give a rough overview of a possible workaround I thought of for this. I haven't actually tried it but in theory it should work. This code is going to be rough and is just to serve as an example.
Instead of sending the calls down through loadUrl(), you queue your javascript calls and then have javascript pull them down. Some thing like:
private final Object LOCK = new Object();
private StringBuilder mPendingJS;
public void execJS(String js) {
synchronized(LOCK) {
if (mPendingJS == null) {
mPendingJS = new StringBuilder();
mPendingJS.append("javascript: ");
}
mPendingJS
.append(js)
.append("; ");
}
}
Instead of calling loadUrl() call that method. (For making this simple I used a synchronized block, but this might be better suited to a different route. Since javascript runs on its own thread, this will need to be thread safe in some way or another).
Then your WebView would have an interface like this:
public class JSInterface {
public String getPendingJS() {
synchronized(LOCK) {
String pendingCommands = mPendingJS.toString();
mPendingJS.setLength(0);
mPendingJS.append("javascript: ");
return pendingCommands;
}
}
}
That returns a String with the pending commands and clears them so they don't get returned again.
You would add it to the WebView like this:
mWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
Then in your javascript you would set some interval in which to flush the pending commands. On each interval it would call JSInterface.getPendingJS() which would return a String of all of the pending commands and then you could execute them.
You could further improve this by adding a check in the execJS method to see if a EditText field exists in the WebView and is in focus. If there is one, then you would use this queueing method, but if there wasn't one in focus then you could just call loadUrl() like normal. That way it only uses this workaround when it actually needs to.
Regarding older APIs (pre 19), I used a similar method to the excepted answer, but slightly different.
First, I keep track of if the keyboard is displayed by using javascript in the webview roughly like so:
document.addEventListener( "focus", function(e){
var el = e.target;
reportKeyboardDisplayedToJava( isInputElement( el ) );
}, true);
document.addEventListener( "blur", function(e){
reportKeyboardDisplayedToJava( false );
}, true);
If the keyboard is displayed, and a js injection is attempted by the Android Java layer – I “defer” that injection. I add it to a string list, allow the user to finish up their input, and then upon the keyboard disappearing, I detect that and execute the backlog of injections.
I could implement cottonBallPaws's idea to use the internals of WebView with reflection, and got it to work for my 4.2 device. There are gracious fallbacks for Android versions older than KitKat.
The code is written in Xamarin, but it should be easily adaptable to native Java code.
/// <summary>
/// Executes a JavaScript on an Android WebView. This method offers fallbacks for older
/// Android versions, to avoid closing of the soft keyboard when executing JavaScript.
/// </summary>
/// <param name="webView">The WebView to run the JavaScript.</param>
/// <param name="script">The JavaScript code.</param>
private static void ExecuteJavaScript(Android.Webkit.WebView webView, string script)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
// Best way for Android level 19 and above
webView.EvaluateJavascript(script, null);
}
else
{
try
{
// Try to do with reflection
CompatExecuteJavaScript(webView, script);
}
catch (Exception)
{
// Fallback to old way, which closes any open soft keyboard
webView.LoadUrl("javascript:" + script);
}
}
}
private static void CompatExecuteJavaScript(Android.Webkit.WebView androidWebView, string script)
{
Java.Lang.Class webViewClass = Java.Lang.Class.FromType(typeof(Android.Webkit.WebView));
Java.Lang.Reflect.Field providerField = webViewClass.GetDeclaredField("mProvider");
providerField.Accessible = true;
Java.Lang.Object webViewProvider = providerField.Get(androidWebView);
Java.Lang.Reflect.Field webViewCoreField = webViewProvider.Class.GetDeclaredField("mWebViewCore");
webViewCoreField.Accessible = true;
Java.Lang.Object mWebViewCore = webViewCoreField.Get(webViewProvider);
Java.Lang.Reflect.Method sendMessageMethod = mWebViewCore.Class.GetDeclaredMethod(
"sendMessage", Java.Lang.Class.FromType(typeof(Message)));
sendMessageMethod.Accessible = true;
Java.Lang.String javaScript = new Java.Lang.String(script);
Message javaScriptCodeMsg = Message.Obtain(null, 194, javaScript);
sendMessageMethod.Invoke(mWebViewCore, javaScriptCodeMsg);
}

Pass and return the values from javascript and android and use as a phone gap plugin

I want to create a plugin for phone which pass and returns the value between javascript and android.
Can anybody suggest any ideas on how to do this?
Actually, this is not very difficult. Here, I will show you how to call native code from javascript within the page and vice-versa:
Calling native code from within web view:
When creating the web view add javascript interface (basically java class whose methods will be exposed to be called via javascript in the web view.
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
The definition of the javascript interface class itself (this is exemplary class I took from another answer of mine and opens video in native intent)
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public void startVideo(String videoAddress){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp"); // The Mime type can actually be determined from the file
activity.startActivity(intent);
}
}
Now if you want to call this code form the HTML of the page you provide the following method:
<script>
function playVideo(video){
window.JSInterface.startVideo(video);
}
</script>
Easy isn't it?
Calling javascript code from native code:
This is also simple suppose in the code of the HTML loaded in WebView you have javascript function defined:
<script>
function function(){
//... do something
}
</script>
Then you call this function through the WebView in the native code like that:
webView.loadUrl("javascript:function()");
Here's a tutorial for creating a PhoneGap Plugin. Also the instructions for the ChildBrowser plugin are especially good.

How can I trigger JavaScript to execute after a Silverlight applet loads?

I am working on a project where I have a lot of interaction between JavaScript and managed code. In fact, I need the JS application to interface with the Silverlight application in the page right from the beginning. So I need the Silverlight application to load before the JS code gets executed.
But while doing so, most of the times I get the error that the object was not found as the Silverlight application has not yet been loaded. So I need the Silverlight to load before the JS executes.
Is there a way I can put a stop on the JS application until the Silverlight loads and then start executing?
First, you need to add an event handler to the Loaded event of your app, from that event handler you can call the javascript function like this:
using System.Windows.Browser;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HtmlPage.Window.CreateInstance("SomeFunction", new string[] { "parameter1", "parameter2" });
}
}
}
Note that you need the System.Windows.Browser namespace to use HtmlPage

Javascript/Silverlight proxy double load delay

I am creating a Silverlight application which will be heavily javascripted against.
To enable JS interaction, I have created the following SL class:
[ScriptableType]
public class JavaScriptProxy
{
private string _version;
// provided for testing SL-JS integration
[ScriptableMember]
public void SmokeTest() { HtmlPage.Window.Alert("Hello world!"); }
}
And loaded it on the constructor of the main SL application:
public App()
{
this.Startup += this.onStartup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
// register javascript bridge proxy
// (must register in constructor so proxy is available immediatly)
HtmlPage.RegisterScriptableObject("JsProxy", new JavaScriptProxy());
}
However, as this is a Javascript-heavy app, it must be loadable via javascript itself.
I.e. something alongs:
// called on body.onLoad
function init() {
var proxy;
var el = document.getElementById("target_canvas");
Silverlight.createObject(..., el, "agApp" ..., {
onLoad: function() {
proxy = agApp.Content.JsProxy;
// ***this line is ok***
proxy.SmokeTest();
}
});
// ***this line fails (of course)***
proxy.SmokeTest();
}
However, this raise the error because agApp.Content.JsProxy is not available fully until the Silverlight onLoad event is fired, thus the JsProxy field is unavailable.
How can I enable access to the JsProxy class immediately as I create the Silverlight instance? Some thing alongs while(_mutex); is probably a bad idea.
I had to this because there will be another layer of abstraction building on the creation of Silverlight app instances, so that function must synchronously load all SL contents in one go.
This is due to Silverlight and JavaScript are operating on seperate threads. Even though you've requested the browser to load the said Silverlight control, it doesn't wait around for Silverlight to finish loading before it proceeds to the next line.
You can only access the JS Proxy after Silverlight has instantiated it so you can either wait for the OnLoad event to fire (but this will only fire after the entire Silverlight.xap is fully loaded) that or after you RegisterScriptableObject fire a JavaScript method called onYourJSProxyNameLoaded() which will put you back inline with the workflow you desire.
HTH.
-
Scott Barnes / Rich Platforms Product Manager / Microsoft.

Categories