您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone UIWebView 中用 JavaScript 取出網頁內容

編輯:iOS 開發綜合

要在 UIWebView 中取得目前頁面的 HTML,不必解析 DOM 樹,直接調用 JavaScript 更快也更省事。核心 API 是 stringByEvaluatingJavaScriptFromString:。

基本用法

// 取得整個頁面的 HTML
NSString *lJs = @"document.documentElement.innerHTML";

// 取得網頁標題
NSString *lJs2 = @"document.title";

UIWebView *lWebView = [self getCurrentWebView];

NSString *lHtml1 = [lWebView stringByEvaluatingJavaScriptFromString:lJs];
NSString *lHtml2 = [lWebView stringByEvaluatingJavaScriptFromString:lJs2];

注意 document.documentElement.innerHTML 拿到的是 <html> 元素內部的內容,不含 <html> 標籤本身,也不含 <!DOCTYPE>。如果你要完整的文件(含 DOCTYPE),可以改用 document.documentElement.outerHTML,或直接用 document.body.innerHTML 只取本文。

更多可用的 JavaScript 片段

下面這些都能透過同一個方法取值,視需求挑用:

thisURL       = document.URL;
thisHREF      = document.location.href;
thisSLoc      = self.location.href;
thisDLoc      = document.location;
thisTLoc      = top.location.href;
thisPLoc      = parent.document.location;
thisTHost     = top.location.hostname;
thisHost      = location.hostname;
thisTitle     = document.title;
thisProtocol  = document.location.protocol;
thisPort      = document.location.port;
thisHash      = document.location.hash;
thisSearch    = document.location.search;
thisPathname  = document.location.pathname;
thisHtml      = document.documentElement.innerHTML;
thisBodyText  = document.documentElement.innerText;   // 頁面純文字
thisBodyText  = document.body.innerText;              // 頁面純文字

其中幾個特別有用:document.location.hash 取的是網址井號「#」後面的片段,常用於單頁應用程式的路由;document.location.search 取得的是「?」後面的查詢字串,可以自己在 App 內解析出參數;document.location.port 則是連接埠號。

反向操作:把資料帶進網頁

同一個 API 也能拿來「執行」而非「取值」。若回傳值為 nil,就代表純粹是副作用呼叫,例如注入一段設定或觸發某個函式:

NSString *js = [NSString stringWithFormat:@"setUserToken('%@');", token];
[lWebView stringByEvaluatingJavaScriptFromString:js];

使用這種字串拼接方式時,若 token 可能包含單引號或換行,記得先自行 escape,否則會產生語法錯誤的 JavaScript。另外,這個 API 只能同步回傳一個字串結果,結構化資料建議回傳 JSON 字串後在原生端解析。

摘自 開心程序

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved