Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject local storage from swift to WKWebview

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?

like image 215
Vivek Kumar Avatar asked Dec 15 '17 12:12

Vivek Kumar


2 Answers

//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
like image 97
Vivek Kumar Avatar answered Nov 15 '22 18:11

Vivek Kumar


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).

like image 26
paulvs Avatar answered Nov 15 '22 20:11

paulvs