I need to pass javascript variable to iOS UIWebView, i did the same very easily with Android, but couldnt do here.
What i need is i will click on a link in webview and that link will in-turn call this JS function buttonClickPAss
with some parameters, and i want what all parameters i passed in the webside to the native swift code. Not just to call that JS function and return its value in swift.
I will add the entire html code below
<html>
<head>
<script type="text/javascript">
function buttonClickPAss(a,b,c)
{
// console.log(action);
return a;// return what i passed to the function that is valueA
}
</script>
</head>
<body>
<b><a href='#' onclick="buttonClickPAss('valueA','valueB','valueC');"> Click here from webview</a></b>
</body>
</html>
this 'valueA','valueB' and 'valueC' are populated when the html page is loaded i need those values in my swift code
I will then load the above html page in webview and will click the link from the webview so that the JS function is called, Because my values are getting populated in the webpage.
this is the tutorial i tried in android
but when i searched for the same in ios i found this tutorial
<script type="text/javascript">
function buttonClickPAss()
{
// console.log(action);
return 'hi from js';
}
</script>
the above is my js code
in native swift i gave this code after loading url
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.url!
let result = webView.stringByEvaluatingJavaScript(from: "buttonClickPAss()")
print("Result = ",result!)
return true
}
the above code is working fine, when i clicked on the link which triggers this js function i got the log in my xcode as 'hi from js'
but i need to pass value to the function buttonClickPAss
so i changed the above codes to this
in JS
<script type="text/javascript">
function buttonClickPAss(a,b,c)
{
// console.log(action);
return a;// return what i passed to the function
}
</script>
and in swift side i changed the above swift code to this
func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let url = request.url!
let result = webView.stringByEvaluatingJavaScript(from: "buttonClickPAss(a,b,c)")
print("Result = ",result!)
return true
}
but in here the "Result" is not printing anything,
I searched other tutorials also everywhere it deals with functions with empty parameters, can anybody help me please
one more note, according to the android tutorial above i could pass the js variables separately in three variables to android, is there a similar mechanism in ios swift? worst case i will make it a json string and return it as a single string
Please help
thanks