0

I have to retrieve all values from the following HTML page like data0, data1, data2 etc,

</head><body onload="OnLoadEvent();">
<form name="form1" action="https://products.cs.co.in/demo/jsp/cs/HResult.jsp" method="post">
    <input type="hidden" name="data0" value="7320851">
    <input type="hidden" name="data1" value="449781">
    <input type="hidden" name="data2" value="">
    <input type="hidden" name="data3" value="ACEE6F7C7">
    <input type="hidden" name="data4" value="">
    <input type="hidden" name="ref" value="">

    <input type="hidden" name="data5">
    <input type="hidden" name="result" value="">
    <input type="hidden" name="data6" value="">
    </form>
    <div align="center" class="text12">
    <br><br>
     Please do not refresh / close the window
    <br><br>
    </div>
</body>)

I am using the below swift code to retrieve all values inside Form ,

 webView.evaluateJavaScript("document.getElementsByName('form1').value") { (result, error) in
        print(result as Any)
        print(error as Any)
    }

But i am receiving nil from result variable. Kindly help on how to retrieve all values inside form using SWIFT language.

0

3 Answers 3

1

I used the following code to get all form values. It worked perfectly.

let jsCode = "" + "function parseForm(form){" +
        "var values='';" +
        "console.log('RESULT 1='+form.elements);" +
        "for(var i=0 ; i< form.elements.length; i++){" +
        "   values+=form.elements[i].name+'='+form.elements[i].value+'&'" +
        "}" +
        "return [values]" +
        "   }" +
        "for(var i=0 ; i< document.forms.length ; i++){" +
        "   parseForm(document.forms[i]);" +
    "};"


    webView.evaluateJavaScript(jsCode, completionHandler: { (result, error) in
        print(result as Any)
        print(error as Any)
        guard let resultArray = result as? [AnyObject] else { return }

    })
Sign up to request clarification or add additional context in comments.

Comments

0

The form has no value, you have to retrieve it from the children input elements. Also not that getElementsByName returns a NodeList and not a single element.

val values = {};
Array.from(document.getElementsByName("form1")[0].children).forEach(input => {
    values[input.getAttribute("name")] = input.value;
});

2 Comments

Thanks for your response. I need to pass this as a string in my delegate like below , webView.evaluateJavaScript("document.getElementsByName('form1').value") { (result, error) in print(result as Any) print(error as Any) } . Can you let me know how to format this to retrieve all values?
Basically you could copy the code and paste it into single quotes. I have no experience in Swift, but I would recommend you to develop the JS seperately and test it (in the browser). Then you can minify it and store it in your swift project. Or you open the file in swift and evaluate this.
0

You need to add a javascript method in your HTML file that will pass form values in your swift code. You can do this with WKScriptMessageHandler.

In your HTML file, add the following code. I named it index.html and placed locally in app.

<head>
    <script type="text/javascript">
        function OnLoadEvent() {
            var test = document.getElementsByName("form1")[0].children
            var values = {};
            Array.from(test).forEach(input => {
                values[input.getAttribute("name")] = input.value;
             });
            window.webkit.messageHandlers.myApp.postMessage({values}); 
        }
    </script>
</head>

window.webkit.messageHandlers.myApp.postMessage({values}); will send from value from javascript to swift. Here myApp is a name of handler that i added in swift code.

Here is swift code

class ViewController: UIViewController, WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            let body = message.body
            if let dict = body as? Dictionary<String, AnyObject> {
                let formData = dict["values"] as! [String: AnyObject]
                for (fieldName, fieldValue) in formData {
                    print("fieldName: \(fieldName) fieldValue: \(fieldValue)")
                }
            }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let config = WKWebViewConfiguration()
        config.userContentController.add(self, name: "myApp")
        let wkWebView = WKWebView(frame: self.view.frame, configuration: config)
        let url = Bundle.main.url(forResource: "index", withExtension: "html")!
        wkWebView.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        wkWebView.load(request)
        self.view.addSubview(wkWebView)
    }
}

6 Comments

Thanks for your response. But without modifying html file, i need to retrieve all values. Is it possible?
@user7413163 when you want to retrieve these values, I mean on button click or on any other event.
In Android, they are using the following code, private final String jsCode = "" + "function parseForm(form){" +"var values='';" + "for(var i=0 ; i< form.elements.length; i++){" + " values+=form.elements[i].name+'='+form.elements[i].value+'&'" +"}" + "var url=form.action;" + "console.log('parse form fired='+values);" +"window.FORMOUT.processFormData(url,values);" + " }" + "for(var i=0 ; i< document.forms.length ; i++){" + " parseForm(document.forms[i]);" + "};"; Its working fine. How to do the same in iOS?
When didFinish Event got fired, i have to retrieve all values
I add "id" tag in input field like <input type="hidden" name="data0" id="data0" value="7320851">. If you try "document.getElementById(\"data0\").value" in webView.evaluateJavaScript method then it'll return input field value. But if you use document.getElementsByName(\"form1\") then it reurn nil data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.