【问题标题】:stringByEvaluatingJavaScriptFromString returns empty string but in safari returns a full stringstringByEvaluatingJavaScriptFromString 返回空字符串,但在 Safari 中返回完整字符串
【发布时间】:2014-07-02 19:01:13
【问题描述】:

我正在使用 js 函数调用 ([self.webview stringByEvaluatingJavaScriptFromString:@"someMethod()"] 调用 stringByEvaluatingJavaScriptFromString

在 iphone 上,它返回一个 empty 字符串,但是当我在 safari 中使用 "Develop -> myphone -> index.html" 进行调试时,相同的调用会按预期返回正确的结果。

我还应该指出,带有该方法的 JS 文件与整个“网站”一样位于设备本地

我如何检查这个?

【问题讨论】:

    标签: javascript ios uiwebview safari


    【解决方案1】:

    首先,您需要确保webView 已正确加载,因此在通知您使用UIWebViewDelegate 方法完成后,请执行任何代码。然后,您必须确保您位于正确的 URL 以使该 JS 方法起作用(您可能会被重定向到移动站点(在 URL 中查找 .m))。如果你是,可能没有任何帮助,所以你必须在移动网站上测试你将在 iPhone 上使用的任何 JS,方法是在你的计算机中打开相同的 URL 并环顾四周。运行这个测试:

    #import "MyWebViewController.h"
    
    @interface MyWebViewController() <UIWebViewDelegate>
    
    // If you have a storyboard
    @property (nonatomic, weak) IBOutlet UIWebView *webView;
    // If you don't have a storyboard
    // @property (nonatomic, strong) UIWebView *webView;
    
    @end
    
    @implementation MyWebViewController
    
    - (void)viewDidLoad
    {
    //    If you don't have a storyboard
    //    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    //    [self.view addSubview:self.webView];
        self.webView.delegate = self;
    }
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        NSLog(@"The URL of the site we are on is: %@", webView.request.URL.absoluteString);
        NSLog(@"Now, I'll evaluate the JS: %@", [webView stringByEvaluatingJavaScriptFromString:@"someMethod()"]);
    }
    
    @end
    

    【讨论】:

    • 我正在使用 [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"htmldir"] 加载本地保存的 html 和 javascript - 并且页面正在根据正确加载到委托方法
    • @AvnerBarr 委托方法有点谎言,因为webViewDidFinishLoad 被多次调用。为了得到最后的负载,检查这个答案:stackoverflow.com/a/2796540/2770572
    • 它调用了一次 - 我想提一下 html 和 java 脚本是本地的
    • 还要提一下,我是在页面加载完成后调用javascript方式
    • @AvnerBarr 什么是JS,什么是URL?
    猜你喜欢
    • 2020-01-27
    • 2020-07-11
    • 2015-05-25
    • 2011-05-09
    • 1970-01-01
    • 2012-07-20
    • 2011-12-15
    • 2020-11-23
    • 2015-12-21
    相关资源
    最近更新 更多