【问题标题】:isSelectorExcludedFromWebScript is never called when setting windowScriptObject设置 windowScriptObject 时从不调用 isSelectorExcludedFromWebScript
【发布时间】:2015-03-23 11:33:23
【问题描述】:

我已尝试按照 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。还是只是其他一些错误?

【问题讨论】:

    标签: objective-c macos cocoa


    【解决方案1】:

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

    【讨论】:

    • 解决方案是什么?
    • @JasonHarrison 是在 Javascript 中调用函数,当你这样做时,首先调用了 Objective-C 注入器方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多