2

I am doing the following:

  • load a WKWebView, lets call this view A
  • ask the user to enter some details
  • ask the user to click a button
  • intercept the click on the WKWebView and PUSH a new view on the application, lets call this view B
  • allow the user to compute a result in the new view and then GO BACK to the previously loaded WKWebView

Now: I would like to add the information that I computed to the previously loaded webpage (view A). The only way I know how to do it is to load a javascript on the loadView() method. However this method is not being called when you navigate back from view B to view A as view A was already loaded. Also forcing a reload when view A reappears would loose the values in the fields that have been edited by the users.

This is the "standard" code I have to call the script:

override func loadView() {
    super.loadView()
    var contentController = WKUserContentController();
    var userScript = WKUserScript(
        source: "setValue(5)",
        injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
        forMainFrameOnly: true
    )

    contentController.addUserScript(userScript)


    var config = WKWebViewConfiguration()
    config.userContentController = contentController

    self.webView = WKWebView(frame: self.containerView!.bounds, configuration: config)
  }  

So now I would need your help to understand how to call the the method "setValue(customparameter)" with a custom value (computed in view B) not in loadView but when the view re-appears.

I can store the value in a singleton object so that's ok. However I do not know how to call / inject the javascript at this stage. Any help?

mm24
  • 9,280
  • 12
  • 75
  • 170

2 Answers2

1

Use WKWebViewConfiguration removeAllUserScripts and then add all the changed scripts (including not changed) again. Remember to use shared or singleton WKWebViewConfiguration instance.

This would solve any refresh or new wkwebview created to have the recent ones

mkumar
  • 111
  • 1
  • 10
1

How about:

self.webView?.evaluateJavaScript("setValue(" + customparameter + ")")