Javascript console.log() in an iOS UIWebView

前端 未结 7 892
深忆病人
深忆病人 2020-11-28 01:10

When writing a iPhone / iPad app with a UIWebView, the console isn\'t visible. this excellent answer shows how to trap errors, but I would like to use the console.log() as w

相关标签:
7条回答
  • 2020-11-28 02:06

    Here's the Swift solution: (It's a bit of a hack to get the context)

    1. You create the UIWebView.

    2. Get the internal context and override the console.log() javascript function.

      self.webView = UIWebView()
      self.webView.delegate = self
      
      let context = self.webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as! JSContext
      
      let logFunction : @convention(block) (String) -> Void =
      {
          (msg: String) in
      
          NSLog("Console: %@", msg)
      }
      context.objectForKeyedSubscript("console").setObject(unsafeBitCast(logFunction, AnyObject.self), 
                                                           forKeyedSubscript: "log")
      
    0 讨论(0)
提交回复
热议问题