Reputation: 89
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
Upvotes: 3
Views: 5352
Reputation: 10012
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView?
func setupWebView(){
webView.navigationDelegate = self
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator?.center = self.view.center
self.view.addSubview(activityIndicator!)
webView.load(URLRequest(url: URL(string: "YourWebSiteLinkHere")!))
webView.configuration.userContentController.add(self, name: "myInterface")
webView.evaluateJavaScript(s, completionHandler: {(string,error) in
print(error ?? "no error")
})
activityIndicator?.startAnimating()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setupWebView()
}
}
extension ViewController: WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("Message received: \(message.name) with body: \(message.body)")
}
}
extension ViewController: WKNavigationDelegate{
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.activityIndicator?.stopAnimating()
self.activityIndicator?.removeFromSuperview()
self.activityIndicator = nil
}
}
In html Code
<script type="text/javascript">
function buttonClickPAss(a,b,c){
//The following line will pass the a to swift
window.webkit.messageHandlers.myInterface.postMessage(a)
}
</script>
In the above I code I registered "myInterface". So that whenever you want to supply data from JavaScript to Swift, you can easily do that.
Now in your example, When user clicks on a link the button; buttonClickPAss will be called. now in your buttonClickPAss method the line window.webkit.messageHandlers.myInterface.postMessage(a)
will pass the variable data to Swift in func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
method.
I think this should be enough to solve your problem. for more information visit this SO
Upvotes: 2