How to call JavaScript Function in objective C(如何在目标 C 中调用 JavaScript 函数)
问题描述
我是 Objective C 的新程序员.我在 Objective C 中添加了一些 html 文件.在这个 html 文件中包含简单的 javascript 函数.我需要通过目标 C 代码调用该函数.我用谷歌尝试了很多时间.但我找不到真正的方法来做到这一点.波纹管包含 html 文件:
I am new programmer to objective C. I added some html file to Objective C. In this html file contains simple javascript function. I need to call that Function through thw objective C code. I tried lot of time by using google. But I could not find real way to do it. Bellow Contains html File :
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
我这样调用这个函数:它是正确的还是错误的??如果错了,该怎么做.请帮忙.
I called this function like this : Is it correct or wrong ?? If it wrong, how to do this. Please help.
NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"first" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
推荐答案
NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"first" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
NSString * jsCallBack = [NSString stringWithFormat:@"myFunction()"];
[webView stringByEvaluatingJavaScriptFromString:jsCallBack];
[webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
如果所有这些代码都是从一个地方调用的,那么它将无法正常工作,因为页面加载是异步的,并且带有 JavaScript 代码的页面此时还没有准备好.尝试在 UIWebViewDelegate 回调方法中调用此方法 [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
–webViewDidFinishLoad:
If all this code called from single place, than it won't work, because page load is asynchronous and page with JavaScript code is not ready at that moment.
Try to call this methods [webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
in UIWebViewDelegate callback method –webViewDidFinishLoad:
这篇关于如何在目标 C 中调用 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在目标 C 中调用 JavaScript 函数
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01