【发布时间】:2018-06-01 11:39:25
【问题描述】:
我需要将 javascript 变量传递给 iOS UIWebView,我在 Android 上也很容易做到这一点,但在这里做不到。
我需要的是我将单击 webview 中的一个链接,该链接将反过来调用这个 JS 函数 buttonClickPAss 并带有一些参数,我想要我在 web 端传递给本机 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 页面时会填充这个 'valueA'、'valueB' 和 'valueC' 我需要在我的 swift 代码中使用这些值
然后,我将在 webview 中加载上述 html 页面,然后单击 webview 中的链接,以便调用 JS 函数,因为我的值正在填充到网页中。
这是我在android中尝试过的教程
但是当我在 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 字符串并将它作为单个字符串返回
请帮忙
谢谢
【问题讨论】:
-
试试 webView.stringByEvaluatingJavaScript(from: "buttonClickPAss('a','b','c')")
-
@SahilManchanda 我试过了,但现在它只返回 'a',不管我通过它返回的'a' :(
-
@milsha,从您为 javascript 共享的代码中,该函数返回“a”
-
@CtrlAltDel 不,它应该返回'a'的值对吗?
-
检查我的答案
标签: javascript ios swift uiwebview