导言

监听网页的按钮的点击事件,并且网页不是咱们招待一声对方就能改的。那么持续。

正文

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.执行结果

点击网页按钮咱们的控制台会打印:

WKWebview与JavaScript 交互(二)监听远程网页点击事件

总结

到此咱们监听网页按钮点击事件的意图能够完成了,(想看交互本地html的能够去看第一张交互本地html链接)。有其他方望共享出来一同学习。

监听了哪个网页的按钮呢?主张去看demo工程,到我的Github下载。