2013-07-02 57 views

回答

9

在NavigationCompleted事件处理程序运行此脚本:

webView.InvokeScriptAsync("eval", new[] 
      { 
       @"(function() 
       { 
        var hyperlinks = document.getElementsByTagName('a'); 
        for(var i = 0; i < hyperlinks.length; i++) 
        { 
         if(hyperlinks[i].getAttribute('target') != null) 
         { 
          hyperlinks[i].setAttribute('target', '_self'); 
         } 
        } 
       })()" 
      }); 
+0

工程就像一个魅力!谢谢! –

+0

嘿!好朋友!感谢它的工作。只是添加了在webView之前等待keywork并使事件异步,它工作完美。 –

1

有一个导航启动事件。它有一个可用于取消导航的取消属性。也许这会对你有用?

http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.navigationstarting

+0

此事件仅适用于Windows 8.1 Preview。 – adheus

+0

对不起。我刚才查看了WebView控件,看不到任何钩子。也许你可以做些什么哈克?你只是想禁用链接?也许可以加载一个iframe的网页,并有一些JavaScript,将禁用所有的链接。循环浏览页面上的锚点并设置其onclicks返回false。 WebView具有此InvokeScript方法,但它看起来像是调用页面上的现有函数,并且不能只注入任何代码。应该直截了当地建立一些HTML并使用NavigateToString方法 – user1985513

+1

只有当您在WebView内部导航时才会调用启动事件。任何请求新窗口的链接都不会收到通知,AFAIK –

0

如果你只是想显示的页面,不允许任何行动,在该页我会去了解一下WebViewBrush上完成。 WebViewBrush基本上会对网站进行截图,用户将无法使用该页面上的任何链接或其他任何内容,它会变成只读页面。我相信这是你所要求的。

上WebViewBrush更多信息可以在这里找到:http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webviewbrush

+0

不,用户可以根据自己的意愿在网站上导航。问题是该网站有一些链接在另一个标签上打开,并导致应用程序调用浏览器。我需要停止调用浏览器而不更改html。 – adheus

0

如果你可以编辑网页和HTML NavigateToString(),然后加入<基本目标= '_空白' 在<头/ > >

+0

在测试了这个解决方案之后,我发现有时候你也会禁用必须和主要网页内容一起处理的CSS和外部文件。 –

6

在Windows 10,您可以使用WebView.NewWindowRequested

private void WebView1_NewWindowRequested(
    WebView sender, 
    WebViewNewWindowRequestedEventArgs args) 
{ 
    Debug.WriteLine(args.Uri); 
    args.Handled = true; // Prevent the browser from being launched. 
} 
1

最近偶然在此我自己,我想补充一点,即使user2269867's答案是一个可行的解决方案,它可能不会在某些情况下工作。

例如,如果用户单击具有target =“_ blank”属性的链接,并且在javascript中调用window.open()函数,则系统浏览器不仅会打开。此外,即使删除所有'target'属性也不会工作,如果页面动态加载一些内容并在脚本执行完毕后更改DOM。

要解决上述所有问题,您需要重写window.open函数,并且不要一次检查'target'属性,而是每次用户单击某个对象。这里是涵盖这些情况的脚本:

function selfOrParentHasAttribute(e, attributeName) { 
    var el = e.srcElement || e.target; 

    if (el.hasAttribute(attributeName)) { 
     return el; 
    } 
    else { 
     while (el = el.parentNode) { 
      if (el.hasAttribute(attributeName)) { 
       return el; 
      } 
     } 
    } 

    return false; 
} 

var targetAttributeName = "target"; 

document.addEventListener("click", function (e) { 
    var el = selfOrParentHasAttribute(e, targetAttributeName); 

    if (el) { 
     if ((el.getAttribute(targetAttributeName) == "_blank") || 
      (el.getAttribute(targetAttributeName) == "_new")) 
     { 
      el.removeAttribute(targetAttributeName); 
     } 
} 
}); 


window.open = function() { 
    return function (url) { 
     window.location.href = url; 
    }; 
}(window.open); 

我的js技能并不理想,所以随时修改。 另外不要忘记,作为kiewic mentioned,对于Windows 10有WebView.NewWindowRequested事件,它解决了这个问题更自然。

相关问题