2017-02-24 71 views
0

我做錯了什麼?如何獲取任何網站的警報消息UWP WebView

我用w3schools.com進行測試。

webView.Navigate(new Uri("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")); 

Package.appxmanifest文件

enter image description here

NavigationCompleted

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) 
{ 
    string result = await sender.InvokeScriptAsync("eval", new string[] { "window.alert = function (AlertMessage) {window.external.notify(AlertMessage)}" }); 
} 

ScriptNotify

private async void WebView_ScriptNotify(object sender, NotifyEventArgs e) 
{ 
    MessageDialog dialog = new MessageDialog(e.Value); 
    await dialog.ShowAsync(); 
} 
+0

你期望發生的,並且它在幹什麼呢? – Adam

+0

我想獲得警報消息[像這樣(截圖)](https://i.stack.imgur.com/IHbud.png) –

回答

0

這裏的問題是相關的到您用於測試的網頁 (https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert)。

如果您檢查此頁面,您會發現「嘗試它」按鈕實際上是名爲「iframeResult」的iframe

<iframe frameborder="0" id="iframeResult" name="iframeResult"> 
 
    <!DOCTYPE html> 
 
    <html> 
 
    <head></head> 
 
    <body contenteditable="false"> 
 
     <p>Click the button to display an alert box.</p> 
 
     <button onclick="myFunction()">Try it</button> 
 
     <script> 
 
      function myFunction() { 
 
       alert("Hello! I am an alert box!"); 
 
      } 
 
     </script> 
 
    </body> 
 
    </html> 
 
</iframe>

所以,當點擊「試試吧」,你要重寫window.alert這是在父框架的alert方法你的代碼將無法正常工作。並且使你的代碼的工作,你可以簡單地將其更改爲iframeResult.window.alert類似如下:

private async void webView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) 
{ 
    string result = await sender.InvokeScriptAsync("eval", new string[] { "iframeResult.window.alert = function(AlertMessage) {window.external.notify(AlertMessage)}" }); 
} 
+0

這不會在任何其他網站的iframe上工作,因爲id'iframeResult'特定於w3schools。 – jerone