开发者

How do I call javaScript from Objective C?

I'm developing a WebKit Safari Plugin with Xcode. How do I call JavaScript from -webPl开发者_如何学CugInStart?


First you should remember the containing view:

+ (NSView *)plugInViewWithArguments:(NSDictionary *)arguments {
    return [[self alloc] initWithArguments:arguments];
}    

- (id)initWithArguments:(NSDictionary*)arguments {
    if((self = [super init])) {
        webView = [[[arguments objectForKey:WebPlugInContainerKey] webFrame] webView];
    }
    return self;
}

When you have that, you can refer to the documentation on "Using JavaScript From Objective-C". E.g.:

- (void)webPlugInStart {
    WebScriptObject *scriptObj = [webView windowScriptObject];
    NSArray *args = [NSArray arrayWithObjects:
        @"someString", [NSNumber numberWithInt:42], nil];
    [scriptObj callWebScriptMethod:@"myJsFunction" withArguments:args];
}


It really is as simple as calling..

WebScriptObject *jsObj = [webView windowScriptObject];
NSString *script = @"$('That's a HUGE vageen.').text('#yourDiv');";
[scriptObject evaluateWebScript:script];

Ta da! And don't let the weird dearth of people doing it - deter you from such sexiness as...

DOMDocument *myDOMDocument = [[webView mainFrame] DOMDocument];
DOMElement *paraBlock = [myDOMDocument getElementById:@"thatDiv"];
DOMElement *newPara = [myDOMDocument createElement:@"p"];
DOMText *newText = [myDOMDocument createTextNode:@"John Resig is a fool."];
[newPara appendChild:newText];
[paraBlock appendChild:newPara];

It's like jQuery! But it's Objective-C. Oh Joy!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜