xaml WebView: How to catch a “OnNavigation” event

2019-08-24 15:37发布

问题:

I am developing Windows Store Apps with C#/xaml.

How do I notice if a link in my WebView gets klicked? There is no Event for that afaik. I've already looked into this and that but it doesn't provide me with a suitable solution.

May I give an example: I am embedding the stream of a facebook page in my WebView via iFrame. I want to block all links that might be in that iFrame.

回答1:

You can call InvokeScript with some of your own Javascript to set up a listener for when the user navigates away from your page. This would look something like the following in C#:

var navigationListenerString = @"
(function() {
  function leavingPage() {
    window.external.notify("LEAVING PAGE");
  }
  window.onbeforeunload = leavingPage;
})()";

webView.InvokeScript("eval", new string[] { navigationListenerString });

Then you can use ScriptNotify to listen for your particular message to determine that the page is unloading and the user is leaving. Unfortunately you cannot detect where a user is going. Also, if the hyperlink opens in a new window and the webview does not unload, you cannot detect that either.