我在我的iOS应用中使用WKWebView来显示HTML字符串。现在,我需要让我的应用捕获HTML页面中被点击的单词。我在HTML中嵌入了一段jQuery代码来捕获单词,然后将页面重定向到包含该单词的伪造URL。在WKWebView的WKNavigationDelegate方法“ decidePolicyFor”中,我解析请求的URL来检索单词。一切工作正常,只是单词本身消失了。我在Safari上尝试了相同的HTML页面,并且重定向URL完全正确,可以在URL地址中确认。我不知道jQuery代码和WKWebView之间有什么问题。任何建议将不胜感激。
我的HTML字符串:
<!DOCTYPE html>
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var p = $('p');
p.click(function(e) {
var sel_obj = window.getSelection(); //it will return an object
sel_obj.modify("move","forward","character");
sel_obj.modify("extend","backward","word");
sel_obj.modify("move","backward","character");
sel_obj.modify("extend","forward","word");
var text = sel_obj.toString().trim();
text = text.toLowerCase();
window.location = "https://www.anonexistent.com/wordclicked/" + text;
});
});
</script>
</header>
<body>
<h1>CLICK-TO-PICK-THE-WORD</h1>
<br/>
<br/>
<p><font size=20>Baa Baa Black Sheep<font></p>
</body>
</html>
我的iOS代码(在Swift中):
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let redirectURLString = navigationAction.request.url?.absoluteString ?? ""
print("redirectURLString: \(redirectURLString)")
if redirectURLString == "about:blank" {
decisionHandler(WKNavigationActionPolicy.allow)
}
else {
decisionHandler(WKNavigationActionPolicy.cancel)
}
}
现在页面可以正确显示。当我在段落中点击“ Sheep”一词时,jQuery可以识别该词并将重定向URL构造为
https://www.anonexistent.com/wordclicked/sheep
我在Safari上验证过的。问题在于,在Xcode中,navigationAction.request.url?.absoluteString仅是
https://www.anonexistent.com/wordclicked/
,缺少“绵羊”一词。