使用evaluateJavaScript从WKWebView获取标题 [英] Getting title from WKWebView using evaluateJavaScript
问题描述
我有一个非常简单/简单的问题,但对 Java 的经验绝对为零.我有一个 WKWebView
,我想使用 javascript document.getElementById
获取页面的标题文本.
我试图从中获取标题的网页具有以下代码:
<身体><div class="工具栏"><h1 id="pageTitle">日程</h1>
此代码已被删节,因此对于任何错误,我深表歉意.
然后我尝试使用 Swift 访问 pageTitle:
func webView(webView: WKWebView, didFinishNavigation 导航: WKNavigation!) {webView.evaluateJavaScript("document.getElementById('pageTitle').value") { (result, error) ->作废如果错误 != nil {打印(结果)}}}
结果返回 nil.经过数小时的搜索,我仍然不知道如何让它发挥作用.任何帮助表示赞赏.
您不应该需要使用 javascript 来检索页面标题.WKWebView 有一个 title
属性将为您检索此内容
title
页面标题.(只读)
斯威夫特var 标题:字符串?{获取}
WKWebView 类符合此属性的键值观察 (KVO).
适用于 iOS 8.0 及更高版本.
I have a very simple/easy question but have absolutely zero experience with java. I have a WKWebView
and I want to get the title text of the page using the javascript document.getElementById
.
The webpage I am trying to get the title from has this code:
<html>
<body>
<div class="toolbar">
<h1 id="pageTitle">Schedules</h1>
</div>
</body>
<html>
This code is abridged so I apologize for any errors.
Then I am trying to access the pageTitle in Swift with:
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementById('pageTitle').value") { (result, error) -> Void in
if error != nil {
print(result)
}
}
}
And the result is returning nil. After hours of searching I still have no idea how to get this to work. Any help is appreciated.
You shouldn't need to use javascript to retrieve the page title. WKWebView has a title
property that will retrieve this for you
title
The page title. (read-only)SWIFT
var title: String? { get }
The WKWebView class is key-value observing (KVO) compliant for this property.
Available in iOS 8.0 and later.
这篇关于使用evaluateJavaScript从WKWebView获取标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!