【问题标题】:Calling Javascript using UIWebView使用 UIWebView 调用 Javascript
【发布时间】:2012-02-11 18:34:27
【问题描述】:

我正在尝试使用该函数在 html 页面中调用 javascript -

View did load function
{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"BasicGraph.html"];
    NSURL *urlStr = [NSURL fileURLWithPath:writablePath];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"BasicGraph" ofType:@"html"];
    [fileManager copyItemAtPath:myPathInfo toPath:writablePath error:NULL];

    [graphView loadRequest:[NSURLRequest requestWithURL:urlStr]];
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];
}

这是 html 页面上的 javascript -

<script>
    function methodName()
      {
         // code to draw graph
      }

但是,函数methodName() 没有被调用,但是在 window.onload = function () 之后一切正常..

我正在尝试将RGraphs 集成到我的应用程序中,Basic.html 是编写 javascript 的 html 页面。

如果有人能帮我解决这个问题,那就太好了。

【问题讨论】:

  • 嘿,如果您不介意,请分享您的示例代码,我可以从本机 iOS 代码调用 rgrpahs 吗?这将非常有帮助。从上周开始,我一直在努力让它发挥作用。
  • 我刚刚创建了一个优雅的demo,主题是Javascript在UIWebview中运行,请参考:creiapp.blogspot.hk/2013/04/uiwebview-javascript.html

标签: javascript uiwebview ios5 rgraph


【解决方案1】:

澄清一点。

.h - 实现 UIWebViewDelegate

@interface YourViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end

.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *path = @"http://www.google.com";
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
    _webView.delegate = self; //Set the webviews delegate to this
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    //Execute javascript method or pure javascript if needed
    [_webView stringByEvaluatingJavaScriptFromString:@"methodName();"];
}

您也可以从情节提要中分配委托,而不是在代码中进行。

【讨论】:

    【解决方案2】:

    简单:您尝试在页面加载之前从 Objective-C 执行 JS 函数。

    在 UIViewController 中实现 UIWebView's delegate method webViewDidFinishLoad: 并在其中调用 [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; 以确保在页面加载后调用该函数。

    【讨论】:

    • 我尝试这样做,但仍然无法正常工作。我已经更改了问题中的代码,但似乎没有任何效果..
    • 这是一个非常有效的问题,根本不是一个愚蠢的问题。谢谢。我忘了设置委托.. 代码现在可以工作了...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多