2013-07-02 59 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事件,它解決了這個問題更自然。

相關問題