1. 程式人生 > >WKWebview與JavaScript 互動(二)監聽遠端網頁點選事件

WKWebview與JavaScript 互動(二)監聽遠端網頁點選事件

引言

監聽網頁的按鈕的點選事件,並且網頁不是我們招呼一聲對方就能改的。那麼繼續。

正文

1.WKUserScript

先介紹WebKit框架一個類WKUserScript:

核心方法,傳入JS程式碼字串,返回給我們一個WKUserScript物件。

/*! @abstract Returns an initialized user script that can be added to a @link WKUserContentController @/link.
 @param source The script source.
 @param injectionTime When the
script should be injected. @param forMainFrameOnly Whether the script should be injected into all frames or just the main frame. */ - (instancetype)initWithSource:(NSString *)source injectionTime:(WKUserScriptInjectionTime)injectionTime forMainFrameOnly:(BOOL)forMainFrameOnly;

WKUserScriptInjectionTime列舉

// 兩個列舉值得解釋

// WKUserScriptInjectionTimeAtDocumentStart Description: Inject the script after the document element is created, but before any other content is loaded.

// WKUserScriptInjectionTimeAtDocumentEnd Description: Inject the script after the document finishes loading, but before other subresources finish loading.
typedef NS_ENUM(NSInteger, WKUserScriptInjectionTime) { WKUserScriptInjectionTimeAtDocumentStart, WKUserScriptInjectionTimeAtDocumentEnd } API_AVAILABLE(macosx(10.10), ios(8.0));

它的功能是可以往webview載入的網頁注入JS程式碼。那麼我們的問題有望解決了。我們就把我們需要的核心程式碼window.webkit.messageHandlers.(messagename).postMessage注入到我們想監聽的網頁。

2.找出網頁按鈕的id

這裡我們用某知名搜尋網站的按鈕做測試。
我們找出網頁按鈕的id,在通過document.getElementById("buttonId");獲取控制元件物件。
在給控制元件新增監聽button.addEventListener('click',addFun,false);

注意:
(1)有的控制元件沒有id屬性,可以選擇class屬性獲取getElementsByClassName。遍歷getElementsByClassName返回的集合確定我們需要的控制元件。
(2)有些網頁pc端和手機端的域名不一樣。所以找網頁控制元件的id或class的時候,同一個網站pc網頁和手機網頁原始碼中id或class屬性不一致的情況。

3.準備注入的JS程式碼

function fun() {
    window.webkit.messageHandlers.%@.postMessage(null);
}
(function(){
    var btn = document.getElementById("%@");
    btn.addEventListener('click',fun,false);
}());

在OC中,上面程式碼以字串的形式傳給WKUserScript

NSString *scriptStr = [NSString stringWithFormat:@"function fun(){window.webkit.messageHandlers.%@.postMessage(null);}(function(){var btn=document.getElementById(\"%@\");btn.addEventListener('click',fun,false);}());", baiduMessage, baiduButtonId];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:scriptStr injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[_userContentController addUserScript:userScript];

4.執行結果

點選網頁按鈕我們的控制檯會列印:
執行結果

總結

到此我們監聽網頁按鈕點選事件的目的可以實現了,(想看互動本地html的可以去看第一張互動本地html連結)。有其他方法望分享出來一起學習。

監聽了哪個網頁的按鈕呢?建議去看demo工程,到我的Github下載。