简体   繁体   English

uiWebview调用javascript函数语法

[英]uiWebview call javascript function syntax

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 //在Android上正确执行

for iOS I am trying, 对于iOS我正在尝试,

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

which would be correct syntax for iOS? 哪个是iOS的正确语法? Thank you. 谢谢。

As per this answer on another similar question , you need to implement the UIWebView delegate 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 UIWebView instance 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 *)script can 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 NSString class 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM