ScriptMessageHandler并不总是在实际设备上调用,在模拟器上工作正常

时间:2016-02-14 21:59:40

标签: ios swift webkit wkwebview

我使用WKWebView,我想在网站满载时收到通知。当webView:didFinishNavigationWKNavigationDelegatedocument.readyState并且我想确定该网站已完全加载时,interactive complete方法会被触发。我想出了使用JavaScript注入的解决方案。这是我的MWE:

import UIKit
import WebKit

class ViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate {

    var webView: WKWebView!

    @IBOutlet weak var loadLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let contentController = WKUserContentController()

        let scriptPath = NSBundle.mainBundle().pathForResource("script", ofType: "js")!
        let scriptString = try! String(contentsOfFile: scriptPath)
        let script = WKUserScript(source: scriptString, injectionTime: .AtDocumentStart, forMainFrameOnly: true)

        contentController.addUserScript(script)
        contentController.addScriptMessageHandler(self, name: "readyHandler")

        let configuration = WKWebViewConfiguration()
        configuration.userContentController = contentController

        webView = WKWebView(frame: CGRect.zero, configuration: configuration)
        webView.navigationDelegate = self
        loadLabel.text = nil
    }

    @IBAction func loadWebsite() {
        webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://stackoverflow.com")!))
        loadLabel.text = "Loading..."
    }

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        print("message received")
        loadLabel.text = "Complete"
    }
}

这是script.js档案的内容:

document.onreadystatechange = function () {
    if(document.readyState === "complete"){
        webkit.messageHandlers.readyHandler.postMessage("");
    }
}
始终在iOS模拟器上调用

userContentController:didReceiveScriptMessage方法,但在实际设备上(在我的情况下为iPhone 6),大部分时间都不会调用它。知道它可能有什么问题,或者检查网站是否完全加载的另一种方式是什么?

1 个答案:

答案 0 :(得分:1)

出于某种原因,您需要将webView添加到可见视图中,以便在设备上工作。如果您不希望webView可见,请添加它,然后将hidden属性设置为true。

对于上面的代码示例:

func viewDidLoad(){
   ...
   webView.hidden = true
   view.addSubview(webView)
}