2013-12-20 64 views
2

我一直在嘗試從WP8的webbrowser獲取元標籤信息,但沒有成功。WP8 - 從WebBrowser獲取元標籤信息

我tryed:

var myDesc = (string)myBrowser.InvokeScript("eval", " $('meta[name=description]').attr('content');"); 

這...

string jsString = ""; 
jsString += " var metas = document.getElementsByTagName('meta'); "; 
jsString += " var data = 'test'; "; 
jsString += " var mLen = metas.length; "; 
jsString += " for(var i=0;i<mLen;i++){ "; 
jsString += " if(metas[i].getAttribute('name').toLowerCase() == 'description'){ "; 
jsString += "  data = metas[i].getAttribute('content'); "; 
jsString += " } "; 
jsString += " } "; 

myBrowser.InvokeScript("eval", new string[] { jsString }); 
var myDesc = (string)myBrowser.InvokeScript("eval", "data;"); 

這...

myBrowser.InvokeScript("eval", new string[] { "var desc = document.getElementsByName('description')[0].getAttribute('content');" }); 

,並與所有的錯誤處理:

{System.SystemException: An unknown error has occurred. Error: 80020101. at Microsoft.Phone.Controls.NativeMethods.ValidateHResult(Int32 hr) at Microsoft.Phone.Controls.WebBrowserInterop.InvokeScript(String scriptName, String[] args) at Microsoft.Phone.Controls.WebBrowser.InvokeScript(String scriptName, String[] args) ...

有人可以幫助我嗎?

最好的問候!

回答

0

首先在xaml中添加WebBrowser並將IsScriptEnabled設置爲true。

<phone:WebBrowser Name="webBrowser" Source="http://www.baidu.com/" IsScriptEnabled="True"/> 

第二寄存器中的事件:LoadedCompeted和ScriptNotify

webBrowser.LoadCompleted += webBrowser_LoadCompleted; 
webBrowser.ScriptNotify += webBrowser_ScriptNotify; 

第三注入的JavaScript代碼

void webBrowser_LoadCompleted(object sender, NavigationEventArgs e) 
{ 
    webBrowser.InvokeScript("eval",@"window.Init=function(){var metas=document.getElementsByTagName('meta');var str='';for(i=0;i<metas.length;i++){str+='name:'+metas[i].getAttribute('name')+',content:'+metas[i].getAttribute('content')+';;}window.external.notify(str);}"); 
    webBrowser.InvokeScript("Init"); 
} 

最後你得到webBrowser_ScriptNotify事件的元信息

void webBrowser_ScriptNotify(object sender, NotifyEventArgs e) 
{ 
    System.Diagnostics.Debug.WriteLine(e.Value); 
} 

希望這會有幫助:D

+0

同樣的錯誤: {System.SystemException:發生未知錯誤。錯誤:80020101. at Microsoft.Phone.Controls.NativeMethods.ValidateHResult(Int32 hr) at Microsoft.Phone.Controls.WebBrowserInterop.InvokeScript(String scriptName,String [] args) at Microsoft.Phone.Controls.WebBrowser.InvokeScript (String scriptName,String [] args) at xxxxxxxx.myBrowser_LoadCompleted ... –

+0

@GabrielGómez';;}在腳本中刪除一個; ...我可以得到meta的正確信息。 – AlexisXu

+0

不!同樣的錯誤... :( –