什么你要找的是参考文件“调用Objective-C的方法从JavaScript”(reference)
基本上,总结它,你必须明确地暴露你的Objective-C类的JavaScript脚本环境。非正式协议是您想要实现的自定义对象,以便能够做到这一点。
一旦你想暴露的对象(例如你的“通知对象”)到JavaScript实现+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
和+ (BOOL)isKeyExcludedFromWebScript:(const char *)name;
你的web视图的控制器/委托现在应该使该对象可用于JavaScript。
例如,在网页视图实例的帧的负载代表:
- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowObject forFrame:(WebFrame *)frame {
// Create the Obj-C object you want JS to be able to access
CustomNotificationCenter *noteCenter = [CustomNotificationCenter sharedNotificationCenter];
// Get the script object that corresponds to "window" in JS
id win = [sender windowScriptObject];
// Add our noteCenter as a property of "window" called "customNotifications"
[win setValue:noteCenter forKey:@"customNotifications"];
}
如果你已经正确地做了一切,你应该能够使用Objective-C的对象在Javascript。举例来说,如果你已经暴露的方法命名为“printNotification:”你noteCenter
,在Javascript这应该工作:
function messageReceived(messageText) {
window.customNotifications.printNotification_("Notification!" + messageText);
}
当然你可以使用低吼,以显示在您的自定义对象 - 对象的通知并执行printNotification
。 (如果你在Mountain Lion,新的通知中心也很棒)。希望有所帮助。
谢谢! * CustomNotificationCenter *有一些问题,因为我不确定如何实现它。我将它添加到我的AppDelegate.h中: - (void)webView:(WebView *)webView didClearWindowObject:(WebScriptObject *)windowObject forFrame:(WebFrame *)frame;并将你的代码添加到AppDelegate.m,但它给了我一个错误*使用未声明的标识符'note center'* – Seb123 2012-08-09 18:48:20
@SebastianRuiz哦 - “CustomNotificationCenter”是我为示例使用的一个示例(非远程)类码。在你的情况下,你会创建你自己的类,赋予它与Growl集成发送通知的功能,然后以暴露伪装类“CustomNotificationCenter”的方式将它公开给Javascript。如果您需要帮助,请随时发布另一个问题! – Vervious 2012-08-09 19:09:56
我正在运行山狮;)所以我应该能够使用内置的通知中心(或嘶嘶声与咆哮)。我不太清楚如何去做你说的话。尤其是整合。如果你可以发表一个例子,我会喜欢它。非常感谢您的帮助! – Seb123 2012-08-09 19:55:12