isSelectorExcludedFromWebScript

isSelectorExcludedFromWebScript

我试图遵循Apple的文章Calling Objective-C Methods From JavaScript,以使WebView中的JS可以访问一些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。还是仅仅是其他错误?

最佳答案

弄清楚了,当JS尝试调用注入的函数或访问注入的键时,将调用webScriptNameForSelectorisSelectorExcludedFromWebScriptisKeyExcludedFromWebScript

关于objective-c - 设置windowScriptObject时,永远不会调用isSelectorExcludedFromWebScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29209186/

10-11 19:48