سؤال

على Windows ، عندما يتم تضمين عنصر التحكم ActiveX "shell.explorer" في تطبيق ما ، من الممكن تسجيل معالج "خارجي" - على كائن ينفذ idispatch ، بحيث يمكن للنصوص على صفحة الويب الاتصال بتطبيق الاستضافة.

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

الآن ، انتقلت إلى تطوير Mac واعتقدت أنه يمكنني الحصول على شيء مماثل من WebKit مضمنًا في تطبيق الكاكاو الخاص بي. ولكن ، لا يبدو أن هناك أي منشأة للسماح للنصوص بالاتصال مرة أخرى إلى تطبيق الاستضافة.

كانت نصيحة واحدة لربط window.alert واحصل على البرامج النصية لتمرير سلسلة رسائل منسقة كسلسلة تنبيه. أنا أيضًا أتساءل عما إذا كان يمكن توجيه WebKit إلى مكون إضافي NPAPI استضافه باستخدام NPPVPlugInscriptablenPobject.

هل فاتني شيء؟ هل من الصعب حقًا استضافة عرض ويب والسماح للنصوص بالتفاعل مع المضيف؟

هل كانت مفيدة؟

المحلول

تحتاج إلى تنفيذ أساليب بروتوكول ويبورت المختلفة. هنا مثال أساسي:

@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'); من بيئة جافا سكريبت و logJavaScriptString: سيتم استدعاء الطريقة.

نصائح أخرى

هذا سهل للغاية مع WebScriptObject API بالاشتراك مع إطار JavaScriptCore.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top