如何在目标C中调用JavaScript函数

如何在目标C中调用JavaScript函数

本文介绍了如何在目标C中调用JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是目标C的新程序员。我在Objective C中添加了一些html文件。在这个html文件中包含简单的javascript函数。我需要通过目标C代码调用该函数。我通过谷歌尝试了很多时间。但我找不到真正的方法来做到这一点。
Bellow包含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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:06