cocoa - 嵌入式Webkit - 脚本回调如何?

标签 cocoa webkit npapi

在 Windows 上,当“Shell.Explorer”ActiveX 控件嵌入到应用程序中时,可以在实现 IDispatch 的对象上注册“外部”处理程序,以便网页上的脚本可以调用托管应用程序。

<button onclick="window.external.Test('called from script code')">test</button>

现在,我转向了 Mac 开发,并认为我可以通过嵌入在我的 Cocoa 应用程序中的 WebKit 获得类似的工作。但是,似乎确实没有任何工具允许脚本回调到托管应用程序。

一个建议是 Hook window.alert 并让脚本将格式化的消息字符串作为警报字符串传递。 我还想知道是否可以使用 NPPVpluginScriptableNPObject 将 WebKit 定向到应用程序托管的 NPAPI 插件。

我错过了什么吗?托管 WebView 并允许脚本与托管交互真的这么难吗?

最佳答案

您需要实现各种 WebScripting 协议(protocol)方法。这是一个基本示例:

@interface WebController : NSObject
{
    IBOutlet WebView* webView;
}

@end

@implementation WebController

//this returns a nice name for the method in the JavaScript environment
+(NSString*)webScriptNameForSelector:(SEL)sel
{
    if(sel == @selector(logJavaScriptString:))
        return @"log";
    return nil;
}

//this allows JavaScript to call the -logJavaScriptString: method
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel
{
    if(sel == @selector(logJavaScriptString:))
        return NO;
    return YES;
}

//called when the nib objects are available, so do initial setup
- (void)awakeFromNib
{
    //set this class as the web view's frame load delegate 
    //we will then be notified when the scripting environment 
    //becomes available in the page
    [webView setFrameLoadDelegate:self];

    //load a file called 'page.html' from the app bundle into the WebView
    NSString* pagePath = [[NSBundle mainBundle] pathForResource:@"page" ofType:@"html"];
    NSURL* pageURL = [NSURL fileURLWithPath:pagePath];
    [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:pageURL]];
}


//this is a simple log command
- (void)logJavaScriptString:(NSString*) logText
{
    NSLog(@"JavaScript: %@",logText);
}

//this is called as soon as the script environment is ready in the webview
- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowScriptObject forFrame:(WebFrame *)frame
{
    //add the controller to the script environment
    //the "Cocoa" object will now be available to JavaScript
    [windowScriptObject setValue:self forKey:@"Cocoa"];
}

@end

在 Controller 中实现此代码后,您现在可以从 JavaScript 环境调用 Cocoa.log('foo');,并且将调用 logJavaScriptString: 方法.

关于cocoa - 嵌入式Webkit - 脚本回调如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288582/

相关文章:

c++ - 适用于 Google Chrome 的简单 hello world NPAPI 插件?

macos - 带有标识符的 NSTableView 单元格始终给出 nil

objective-c - WebView 中的本地存储不是持久的

javascript - Safari 是否将浏览器窗口名称与打开它的域关联起来?

webkit - WebKitFormBoundary 后面的随机字符串是什么意思?

dom - 是否有可以在 webkit 中使用的 DOMAttrModified 的替代方法

c - 加载插件后是否可以将控制权交还给浏览器

macos - 模拟系统范围热键的按键

cocoa - 移动无边框 NSWindow 完全被 Web View 覆盖

javascript - Firefox 是否支持 enablePrivilege ("UniversalBrowserRead")?