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

本文介绍了如何在iOS应用中使用WKWebView监听远程网页的按钮点击事件,通过WKUserScript注入JavaScript代码,实现与网页的交互。详细步骤包括确定网页按钮ID、编写JS代码并注入,最终成功监听并响应网页按钮点击。

引言

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

正文

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下载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值