Reputation: 406
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})
Any idea what's wrong?
Upvotes: 6
Views: 4504
Reputation: 406
//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.sstatic.net/tzGUc.png
Upvotes: 6
Reputation: 12053
Since evaluateJavaScript
executes code as if from the Console of Safari Inspector, the javascript:
is not used.
On a side note, the javascript:
prefix is used to execute JavaScript from a URL (you can test this by typing (not copy-pasting) javascript: alert('howdy')
into the address bar of your browser).
Upvotes: 1