xcode uiWebview 调用javascript函数语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11921656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:12:51  来源:igfitidea点击:

uiWebview call javascript function syntax

javascriptiphoneiosxcode

提问by Jaume

I am migrating my app from android to iOS and for following line, compiler returns me an error on iOS,

我正在将我的应用程序从 android 迁移到 iOS,对于以下行,编译器在 iOS 上返回一个错误,

webviewA.loadUrl("javascript:setVars(\"" + var1 + "\",\"" + var2 + "\")");//properly executed on Android

webviewA.loadUrl("javascript:setVars(\"" + var1 + "\",\"" + var2 + "\")");//在Android上正确执行

for iOS I am trying,

对于 iOS 我正在尝试,

[webViewA stringByEvaluatingJavaScriptFromString:@"javascript:setVars(\"" + var1 + "\",\""  + var2 +  "\")"];

which would be correct syntax for iOS? Thank you.

哪个是 iOS 的正确语法?谢谢你。

回答by jstr

As per this answer on another similar question, you need to implement the UIWebViewdelegate method webViewDidFinishLoad:, and in there implement [myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptCode()"].

根据另一个类似问题的答案,您需要实现UIWebView委托方法webViewDidFinishLoad:,并在那里实现[myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptCode()"]

In order for this to work you need to set the delegate on the UIWebViewinstance and implement the delegate method mentioned above so that the JavaScript is executed after the page has loaded.

为了使其工作,您需要在UIWebView实例上设置委托并实现上述委托方法,以便在页面加载后执行 JavaScript。

The documentation for - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)scriptcan be found here.

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script可在此处找到的文档。

Now for the other part of your question (thanks for clarifying!).. to concatenate strings in Objective-C you can use the NSStringclass method stringWithFormat:.

现在对于您问题的另一部分(感谢您的澄清!)。要在 Objective-C 中连接字符串,您可以使用NSString类方法stringWithFormat:

For example, to pass two Objective-C values to a JavaScript string, you could do something like this:

例如,要将两个 Objective-C 值传递给 JavaScript 字符串,您可以执行以下操作:

// Substitute your Objective-C values into the string
NSString *javaScript = [NSString stringWithFormat:@"setVars('%@', '%@')", var1, var2, nil];

// Make the UIWebView method call
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];