如何在 UIWebView 中为 DOM 事件添加监听器?例如以下 HTML 代码:
在加载UIWebView中的HTML的IOS应用程序中,是否可以注册一个侦听按钮单击事件的监听器?
<button type="button" id="button1">Try it</button>
在加载UIWebView中的HTML的IOS应用程序中,是否可以注册一个侦听按钮单击事件的监听器?
// In the UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (/* when the loaded url is the target */) {
NSString *js = @"document.getElementById('button').click = function() { window.location = 'my-protocol://dummmy.com/maybe/some/data';}";
[webView stringByEvaluatingJavaScriptFromString: js];
}
}
// In the UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (/* when the url of the request is the crafted url */) {
// call your objc method...
}
}
UIWebView
中拦截链接被点击的Swift方法:class ViewController: UIViewController, UIWebViewDelegate { //... }
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
//...
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if (currentURL?.lowercased().range(of:"some/url") != nil) {
webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('a')[0].onclick = function() {window.location = 'injected://loadPDF1'; return false;}")
}
}
// Sent before a web view begins loading a frame.
func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
// intercept all injected page calls
if (shouldStartLoadWith.url?.scheme == "injected") {
return false;
}
return true;
}
document
对象上绑定按钮的onclick事件监听器。 - Egist Li