javascript 使用evaluateJavaScript从WKWebView获取标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32751629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:42:41  来源:igfitidea点击:

Getting title from WKWebView using evaluateJavaScript

javascriptiosswiftwkwebview

提问by Tamarisk

I have a very simple/easy question but have absolutely zero experience with java. I have a WKWebViewand I want to get the title text of the page using the javascript document.getElementById.

我有一个非常简单/简单的问题,但对 Java 的经验绝对为零。我有一个WKWebView,我想使用 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:

然后我尝试使用以下命令访问 Swift 中的 pageTitle:

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.

结果是返回零。经过数小时的搜索,我仍然不知道如何让它发挥作用。任何帮助表示赞赏。

回答by SilkyPantsDan

You shouldn't need to use javascript to retrieve the page title. WKWebViewhas a titleproperty that will retrieve this for you

您不需要使用 javascript 来检索页面标题。WKWebView有一个title属性可以为你检索这个

https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKWebView_Ref/#//apple_ref/occ/instp/WKWebView/title

https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKWebView_Ref/#//apple_ref/occ/instp/WKWebView/title

titleThe 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.

title页面标题。(只读)

迅速 var title: String? { get }

WKWebView 类符合此属性的键值观察 (KVO)。

在 iOS 8.0 及更高版本中可用。

回答by superarts.org

As mentioned by @SilkyPantsDan, if you are just interested in the title, there's no need to use JS. Firstly you start observing:

正如@SilkyPantsDan 所提到的,如果您只是对 . 感兴趣title,则无需使用 JS。首先你开始观察:

override func viewDidLoad() {
    super.viewDidLoad()
    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil)
}

And handle your logic when titleis updated:

并在title更新时处理您的逻辑:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
        title = webView.title
    }
}

Finally you should stop observing if you are supporting iOS 8.0, as observers are not removed automatically before iOS 9.0:

最后,如果您支持 iOS 8.0,您应该停止观察,因为在 iOS 9.0 之前观察者不会自动删除:

deinit {
    webView.removeObserver(self, forKeyPath: "title")
    //webView.removeObserver(self, forKeyPath: "estimatedProgress")
}

回答by Kris Roofe

In your code when there is some error, then the code will print the result. This'll print nothing when there is no error occuer.

在您的代码中出现错误时,代码将打印结果。当没有错误发生时,这将不打印任何内容。

So change you code to this, everything works well.

因此,将您的代码更改为此,一切正常。

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {

    webView.evaluateJavaScript("document.getElementById('pageTitle').innerHTML") { (result, error) -> Void in
        if error != nil {
            print(error)
        }
        print(result)
    }
}

回答by dopcn

Use Node.textContent to get a correct copy of text nodes contents.

使用 Node.textContent 获取文本节点内容的正确副本。

webView.evaluateJavaScript("document.getElementById('pageTitle').textContent") { (result, error) -> Void in
    if error != nil {
        print(result)
    }
}

回答by brassic_lint

I used this same code snippet, and worked out the issue... It'll only print the result if it's "nil"!

我使用了相同的代码片段,并解决了这个问题......如果结果为“nil”,它只会打印结果!

Try:

尝试:

webView.evaluateJavaScript("document.getElementById('pageTitle').textContent") { (result, error) -> Void in
    if error == nil {
        print(result)
    }
}

回答by Ajharul Islam

this code is works for me :

这段代码对我有用:

webView.evaluateJavaScript("document.title').textContent") { (result, error) -> Void in
    if error == nil {
        print(result)
    }
}