javascript - window.location 未设置/webView shouldStartWithLoadRequest 未被调用

标签 javascript ios objective-c uiwebview

我一直在研究我在 StackOverflow 上找到的几个主题,但我似乎无法正确处理。

我的应用程序在本地存储一个 HTML 页面,我正在尝试让一些 Javascript 与我的 obj-c 代码一起工作。

这是我的 JavaScript 文件:

<button onclick="myFunction()">Try it</button>


<script>
function myFunction()
{
    window.location.href = "ios:webToNativeCall";
    alert(window.location.href);
}
</script>

这是我的obj-c方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"test");
    if ([[[request URL] absoluteString] hasPrefix:@"ios:"]){
        NSLog(@"test");
        [self webToNativeCall];
        return NO;
    }

我会发布两个单独的主题,但我感觉这些问题是相互关联的。在 JS 文件中,警报打印出我系统中 .html 文件的正确路径。 NSLog(@"test") 都没有被执行。

我已经设置了 WebView 委托(delegate):

@interface WebBrochureViewController : UIViewController <UIWebViewDelegate>

感谢任何帮助或提示。

最佳答案

您的 Storyboard 设置可能有问题。您应该首先尝试一个简单的案例作为概念证明,然后学习如何将其适应更大的图景。

这里有一个很好的简单 View Controller 来解决你的问题。

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

@end

@implementation MyViewController

- (void)loadView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

    [view addSubview:({
        UIWebView *webView = [[UIWebView alloc] initWithFrame:view.bounds];
        webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        webView.delegate = self;
        self.webView = webView;
    })];
    self.view = view;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSAssert(url!=nil, @"Could not find URL for index.html");
    NSData *data = [NSData dataWithContentsOfURL:url];
    [self.webView loadData:data
                  MIMEType:@"text/html"
          textEncodingName:@"utf-8"
                   baseURL:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"[%@] Delegate method started.", NSStringFromSelector(_cmd));
    if ([request.URL.scheme isEqualToString:@"ios"]) {
        NSLog(@"[%@] Communication Received.", NSStringFromSelector(_cmd));
        return NO;
    }
    return YES;
}

@end

关于javascript - window.location 未设置/webView shouldStartWithLoadRequest 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296934/

相关文章:

objective-c - 如何为按钮标题的一半着色

ios - 是否可以打开 Tweetbot 并分享图片?

javascript - jquery 在滚动和加载页面时添加不透明度

javascript - angular-tree-component json 到可接受的格式并动态创建复选框或单选按钮

javascript - MySQL COUNT 性能与 JavaScript 对象/数组的比较

ios - 当我在 iphone 5 屏幕上运行程序时 xcode 看起来像 iphone 4

javascript - Cordova 应用程序启动 whatsapp

objective-c - 设置 NSSetUncaughtExceptionHandler 时出错 ..

javascript - 二元运算在同一台机器上的不同输出

ios - 带有自定义 ProgressImage 的 UIProgressView 拉伸(stretch)不正确。怎么修?