How to debug javascript code inside a WKWebView

2019-04-20 12:27发布

I'm having some trouble with running a webapp in a WKWebView (specifically: some buttons are not responding). I used this tutorial as a guide and did succeed in having the webview display my webapp. So now I want to debug the javascript code.

I know the webapp works, since I've tried it in both an android webview as well as countless browsers (including safari on the iPad simulator I'm using). After some quick googling, I found out how to debug javascript inside a UIWebView using Safari. Sadly This doesn't seem to work with the new WKWebView.

When I navigate to Develop->iPad Simulator I'm told that there are 'No Inspectable Applications'. I've tried the very same thing with a simple app with a UIWebView and debugging through safari works perfectly there.

Is there a way to debug javascript code within a WKWebView?

To reproduce my problems (using swift), start a new single screen project in xCode 6, copy the code (courtesy of kinderas) provided below in your ViewController.swift file and drag the outlet to View under View Controller in the document outline in the Main.storyboard file. Refer to the tutorial I linked above in case of confusion.

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

3条回答
孤傲高冷的网名
2楼-- · 2019-04-20 13:00

open the website or html page in your webview, then open safari. click develop, then go to simulator and you will find your website title there. once you open it you will see the javascript debugger, console and everything else you can dream of.

查看更多
手持菜刀,她持情操
3楼-- · 2019-04-20 13:11

UPDATE: 2017/09/11

Recent versions of Safari can do this. Just enable the develop menu in Safari - developer.apple.com

OLD:

You need to install the nightly build of Safari and use that. I was having the same problem with an app I'm developing. Once I installed the nightly build, I now use that and all of my WKWebViews show up in the develop menu.

Hope that's the part you were missing!

查看更多
我想做一个坏孩纸
4楼-- · 2019-04-20 13:11

You can try http://jsconsole.com/

Execute :listen and it gives you a script tags to paste in your webpage.

Every console.log you have in that page will give their output to this page.

If you close jsconsole page, next time you should change script src in html code but you can listen to that script src too:

:listen XXXXX-XXXXX-XXXX-XXXXX

I hope it helps.

查看更多
登录 后发表回答