2

I have been trying to set a cookie for WKWebView using Swift 3 in order to pass a device token to a server.

The code I've been trying to get working in order to set the cookie is as follows:

wkWebView.evaluateJavaScript("document.cookie='access_token=your token';domain='your domain';") { (data, error) -> Void in
    print("data: \(data)")
    print("error2: \(error)")
    wkWebView.reload()
}

However, I'm stuck here because this code produces the following error output:

error2: Optional(Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=0, WKJavaScriptExceptionMessage=SecurityError (DOM Exception 18): The operation is insecure., WKJavaScriptExceptionSourceURL=undefined, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=0})

rmaddy
  • 314,917
  • 42
  • 532
  • 579
lundzern
  • 417
  • 3
  • 11
  • Are you using a webserver or local file (https://stackoverflow.com/a/2705057/2124535) ? – nathan Aug 28 '17 at 19:00
  • I am using a webserver, Node.Js serving an Angular app – lundzern Aug 28 '17 at 19:00
  • Try this solution: https://stackoverflow.com/a/26577303/2124535 If you need to set the cookie after creating the webview, check the second scenario. – nathan Aug 28 '17 at 19:02
  • Thanks I'll check it out but its not clear to me what users solution you wan't me to try? – lundzern Aug 28 '17 at 19:04
  • 1
    matt'r response – nathan Aug 28 '17 at 19:05
  • Mattrs response would be similar to dooing; request.setValue("Wolverine", forHTTPHeaderField: "X-Men-Header") (after creating a NSURLMutableRequest) and for me the above line of code has not been working like I would hope. – lundzern Aug 29 '17 at 10:49

1 Answers1

2

I ended up setting the cookie by injecting a script into WKWebView at runtime, which sets the Firebase device token, which is the string I want to pass to my server, as a local storage item.

The code I've ended up with is as follows;

To set the local storage in WKWebView:

let addCookieScript="localStorage.setItem('device', '\(self.tokenFirebase)');\nconsole.log(localStorage.getItem('token'));\nconsole.log(localStorage.getItem('userId'));\n"
let script: WKUserScript = WKUserScript(source: addCookieScript as String, injectionTime: .atDocumentEnd, forMainFrameOnly: false)

Adding the script to the WKWebView:

userContentController.addUserScript(script)

After this it is just a matter of loading the WKWebView as normal, and to monitor the local storage of the session through the Safari Developer Tool

lundzern
  • 417
  • 3
  • 11