如何将值从javascript传递到iOS UIWebView

问题描述 投票:1回答:1

我需要将javascript变量传递给iOS UIWebView,我在Android上也很容易做到,但是不能在这里做。

我需要的是我将点击webview中的链接,该链接将反过来调用这个JS函数buttonClickPAss一些参数,我想要我在webside中传递的所有参数到本机swift代码。不只是调用JS函数并在swift中返回其值。

我将在下面添加整个HTML代码

<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>

加载html页面时会填充此'value','value'和'valueS',我需要在swift代码中使用这些值

然后我将在webview中加载上面的html页面,并点击webview中的链接,以便调用JS函数,因为我的值已经填充在网页中。

这是我在android中尝试的教程

https://capdroidandroid.wordpress.com/2015/07/03/how-send-data-from-javascript-to-native-android-app/

但是当我在ios中搜索相同的内容时,我发现了本教程

<script type="text/javascript">
            function buttonClickPAss()
            {
              //  console.log(action);

                return 'hi from js';
            }
            </script>

以上是我的js代码

在本机swift中,我在加载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
}

上面的代码工作正常,当我点击触发这个js函数的链接时,我在我的xcode中记录为'hi from js'

但我需要将值传递给函数buttonClickPAss所以我将上述代码更改为此

在JS中

<script type="text/javascript">
            function buttonClickPAss(a,b,c)
            {
              //  console.log(action);

                return a;// return what i passed to the function
            }
            </script>

在迅速的一面,我将上面的快速代码更改为此

 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
}

但在这里“结果”不打印任何东西,

我搜索其他教程,它处理空参数的函数,任何人都可以帮助我

还有一点需要注意,根据上面的android教程,我可以将三个变量中的js变量分别传递给android,ios swift中是否有类似的机制?最坏的情况我将使它成为一个json字符串并将其作为单个字符串返回

请帮忙

谢谢

javascript ios swift uiwebview
1个回答
1
投票
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
    }
}

在HTML代码中

<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>

在上面我的代码我注册了“myInterface”。因此,无论何时您想要将数据从JavaScript提供给Swift,您都可以轻松实现。现在在您的示例中,当用户单击链接按钮时; buttonClickPAss将被调用。现在在你的buttonClickPAss方法中,行window.webkit.messageHandlers.myInterface.postMessage(a)func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)方法中的变量数据传递给Swift。

我认为这应该足以解决您的问题。欲了解更多信息,请访问这个SO

© www.soinside.com 2019 - 2024. All rights reserved.