如何从Objective C调用javaScript?

时间:2010-05-25 16:23:20

标签: javascript objective-c safari webkit

我正在使用Xcode开发一个WebKit Safari插件。如何从-webPlugInStart调用JavaScript?

2 个答案:

答案 0 :(得分:1)

首先你应该记住包含视图:

+ (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;
}

如果有,请参阅"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];
}

答案 1 :(得分:1)

这真的就像打电话一样简单。

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

Ta da!并且不要让人们做这种奇怪的缺乏 - 阻止你像 sexiness 那样......

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];

就像jQuery! 但它是Objective-C。哦,欢乐!