Search code examples
webkitios14

WKWebView does not work on evaluateJavaScript() form submit


In our app we are dynamically creating a form with input fields and relying on evaluateJavaScript() function to submit the form and load the url in the decision handler. This approach has been working fine and seems to have been broken in iOS 14 (tested beta 3, 4, 5). Prior to iOS 14 the code below resulted in decidePolicyFor delegate function getting called but it doesn't get called in iOS 14.

The only solution I have found so far is to add the ‘form’ to the dom before calling form.submit() (commented line in javascriptForExecution() function)

Any other suggestions/ideas?

override func viewDidLoad() {
    super.viewDidLoad()
    webView.evaluateJavaScript(javascriptForExecution()) { (result, error) in
        if error != nil {
            print("Javascript execuption failed: \(error.debugDescription)")
        }
    }
}

private func javascriptForExecution() -> String {
    return """
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'https://www.example.com/';
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'Name';
    input.value = 'NameValue';
    form.appendChild(input);
    //document.body.appendChild(form)
    form.submit();
    """
}

// WKNavigationDelegate
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.request.url?.absoluteString == "https://www.example.com/" {
        if let url = URL(string: "https://www.apple.com") {
            webView.load(URLRequest(url: url))
        }
        decisionHandler(.cancel)
        return
    }
    decisionHandler(.allow)
}

Solution

  • Response from Apple below

    We reviewed your report and determined the behavior you experienced is currently functioning as intended. This was an intentional change to align with the HTML spec

    WKWebView is working properly, and that this change in behavior is due to WebKit aligning more closely with the HTML5 standard, which requires that forms only be submitted if they are ‘connected’ (i.e., part of the DOM).

    HTML Standard PR: https://github.com/whatwg/html/pull/2613

    The form submit button needs to be associated with a document, and in the document’s node tree. https://dom.spec.whatwg.org/#connected