首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将值从javascript传递到iOS UIWebView

如何将值从javascript传递到iOS UIWebView
EN

Stack Overflow用户
提问于 2018-06-01 19:39:26
回答 1查看 3.9K关注 0票数 2

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

我需要的是我将点击webview中的一个链接,该链接将反过来调用此JS函数buttonClickPAss与一些参数,我想要的所有参数,我在网站上传递给本地的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>

这'valueA','valueB‘和'valueC’是在加载html页面时填充的,我需要在我的快速代码中使用这些值

然后,我将在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>

在swift方面,我将上面的swift代码更改为

 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字符串,并将其作为单个字符串返回。

请帮帮忙

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-06-01 20:15:47

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50642609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档