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!
精彩评论