13

Windowsでは、「Shell.Explorer」ActiveXコントロールがアプリケーションに埋め込まれている場合、IDispatchを実装するオブジェクトに「外部」ハンドラーを登録して、Webページ上のスクリプトがホスティングアプリケーションを呼び出すことができるようにすることができます。

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

さて、iveはMac開発に移行し、Cocoaアプリケーションに埋め込まれたWebKitから同様の機能を得ることができると考えました。ただし、スクリプトがホスティングアプリケーションにコールバックできるようにする機能は実際にはないようです。

アドバイスの1つは、window.alertスクリプトをフックして取得し、フォーマットされたメッセージ文字列をアラート文字列として渡すことでした。また、NPPVpluginScriptableNPObjectを使用して、WebKitをアプリケーションでホストされているNPAPIプラグインに転送できるかどうかも疑問に思っています。

私は何かが足りないのですか?WebViewをホストし、スクリプトがホストと対話できるようにするのは本当に難しいですか?

4

2 に答える 2

31

さまざまなWebScriptingプロトコルメソッドを実装する必要があります。基本的な例を次に示します。

@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

このコードをコントローラーに実装した後Cocoa.log('foo');、JavaScript環境から呼び出すことができ、logJavaScriptString:メソッドが呼び出されます。

于 2010-02-19T00:30:36.330 に答える
1

これは、 WebScriptObjectAPIをJavaScriptCoreフレームワークと組み合わせて使用​​すると非常に簡単に実行できます。

于 2010-02-18T16:23:34.877 に答える