Objective-C/Cocoa windowScriptObject 命令在加载的页面不起作用



我正在尝试让'windowScriptObject'工作,这是我下面的Objective-C代码:

- (void)consoleLog:(NSString *)aMessage {
    NSLog(@"JSLog: %@", aMessage); }
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector {
    if (aSelector == @selector(consoleLog:)) {
        return NO;
    }
    return YES; }
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
    NSLog(@"Did finnish load...");
    scriptObject = [sender windowScriptObject];
    //obviously, this returns undefined
    NSLog(@"Object: %@",[scriptObject evaluateWebScript:@"MyApp"]);
    //set the value of MyApp
    [scriptObject setValue:self forKey:@"MyApp"];
    //this now returns the value
    NSLog(@"Object: %@",[scriptObject evaluateWebScript:@"MyApp"]);


    //this command now works from here
    [scriptObject evaluateWebScript:@"MyApp.consoleLog_('Test');"]; 
}

上面的代码在我注入JavaScript时有效(评估WebScript

这是控制台输出的内容:

2012-12-06 08:03:05.605 BetterDesktop[8669:303] Did finnish load...
2012-12-06 08:03:05.605 BetterDesktop[8669:303] Object: undefined
2012-12-06 08:03:05.606 BetterDesktop[8669:303] Object: <WidgetsDelegate: 0x10133de60>
2012-12-06 08:03:05.607 BetterDesktop[8669:303] JSLog: Test

该命令有效,但是当我使用页面时它不起作用。

<html>
<head>
<script type="text/javascript">
if (typeof(MyApp) != "undefined"){
document.write('<br/><h1>hi</h1>');
MyApp.consoleLog_('Test from HTML');
}
else{
document.write('<br/><h1>Not Defined</h1>');
}
</script>
</head>
<body>
</body>
</html>

它认为"MyApp"是未定义的,有什么建议吗?

(顺便说一下,WebView 没有连接到这个类,它只是委托)

您应该从 -webView:didClearWindowObject:forFrame: WebFrameLoadDelegate 方法中而不是在 -webView:didFinishLoadForFrame: 中将对象注入到 WebView 中。在调用 didClearWindowObject 之前,不保证已正确初始化window对象。

最新更新