在设置windowScriptObject时,永远不会调用isSelectorExcludedFromWebScript

时间:2015-03-23 11:33:23

标签: objective-c macos cocoa

我试图遵循Apple文章Calling Objective-C Methods From JavaScript,让JS在WebView中访问一些Objective-c函数。

使用如下所示的中间层对象:

// FILE: RTFInterop.h

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@protocol RTFInteropDelegate <NSObject>
@end

@interface RTFInterop : NSObject

- (id)initWithWebView:(WebView*)webView andDelegate:(id<RTFInteropDelegate>)delegate;
- (void)onHeightUpdated:(int)height;
- (void)onAnswerBlocksUpdated:(NSString*)answerBlockJSON;

+ (NSString *)webScriptNameForSelector:(SEL)sel;
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
+ (BOOL)isKeyExcludedFromWebScript:(const char *)name;

@end

// FILE: RTFInterop.m

#import "RTFInterop.h"

@implementation RTFInterop {
    WebView *webView;
    id<RTFInteropDelegate> delegate;
}

- (id)initWithWebView:(WebView*)aWebView andDelegate:(id<RTFInteropDelegate>)aDelegate {
    self = [self init];

    if (self) {
        webView = aWebView;
        delegate = aDelegate;
        [webView.windowScriptObject setValue:self forKey:@"RTFInterop"];
    }

    return self;
}

+ (NSString *)webScriptNameForSelector:(SEL)sel {
    NSString *name;

    if (sel == @selector(onHeightUpdated:)) {
        name = @"onHeightUpdated";
    } else if (sel == @selector(onHeightUpdated:)) {
        name = @"onAnswerBlocksUpdated";
    }

    return name;
}

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel {
    if (sel == @selector(onHeightUpdated:)) {
        return NO;
    } else if (sel == @selector(onHeightUpdated:)) {
        return NO;
    }

    return YES;
}

+ (BOOL)isKeyExcludedFromWebScript:(const char *)name {
    return YES;
}

// Called from JS
- (void)onHeightUpdated:(int)height {

}

// Called from JS
- (void)onAnswerBlocksUpdated:(NSString*)answerBlockJSON {

}

@end

示例用法是这样的:

self.webView = [[WebView alloc] init];
self.interop = [[DXRichTextInterop alloc] initWithWebView:self.webView andDelegate:nil];

NSURL *url = [NSURL URLWithString:@"file:///Users/example/dev/testembedd.html"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

[self.webView.mainFrame loadRequest:urlRequest];
[self.webView setFrame:CGRectMake(0, 0, 100, 100)];

webView显示正确,但问题是它似乎没有注入JavaScript,isSelectorExcludedFromWebScript:中的断点永远不会被击中。

问题:在嵌入JS时是否有一些要求,我错过的文章中没有包含这些要求?比如在WebView生命周期中你可以注入JS。或者只是其他一些错误?

1 个答案:

答案 0 :(得分:2)

想出来,当JS尝试调用注入的函数或访问注入的键时,调用webScriptNameForSelectorisSelectorExcludedFromWebScriptisKeyExcludedFromWebScript