My Swift Code:
self.webView.evaluateJavaScript("javascript: localStorage.setItem('usr_dtls', 'vivek')") { (result, error) -> Void in
print(result)
print(error)
}
Error message in cosole:
nil
Optional(Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SecurityError (DOM Exception 18): The operation is insecure., WKJavaScriptExceptionColumnNumber=25, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred})
知道什么是错的吗?
答案 0 :(得分:0)
由于evaluateJavaScript
执行代码就好像来自Safari Inspector的控制台,因此不使用javascript:
。
在旁注中,javascript:
前缀用于从URL执行JavaScript(您可以通过键入(而不是复制粘贴)javascript: alert('howdy')
来测试浏览器的地址栏。)
答案 1 :(得分:0)
//Found a solution.Execute Javascript after webView finished loading
//Sample code:
self.webView.navigationDelegate = self
func webView(_ webView: WKWebView,
didFinish navigation: WKNavigation!)
{
self.webView.evaluateJavaScript("localStorage.setItem('usr_dtls', 'vivek')") { (result, error) -> Void in
print("Finished navigation and Local storage injection.")
}
}
//Run the app and debug using Safari Technology Preview
//You will see the injected data as Show in the image below:
[![Screenshot][1]][1]
[1]: https://i.stack.imgur.com/tzGUc.png