![](/img/trans.png)
[英]How to call an Objective-C method from Javascript in a Cocoa/WebKit app?
[英]Objective-C/Cocoa windowScriptObject commands not working from loaded page
我試圖讓'windowScriptObject'工作,這是我的Objective-C代碼如下:
- (void)consoleLog:(NSString *)aMessage {
NSLog(@"JSLog: %@", aMessage); }
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector {
if (aSelector == @selector(consoleLog:)) {
return NO;
}
return YES; }
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
NSLog(@"Did finnish load...");
scriptObject = [sender windowScriptObject];
//obviously, this returns undefined
NSLog(@"Object: %@",[scriptObject evaluateWebScript:@"MyApp"]);
//set the value of MyApp
[scriptObject setValue:self forKey:@"MyApp"];
//this now returns the value
NSLog(@"Object: %@",[scriptObject evaluateWebScript:@"MyApp"]);
//this command now works from here
[scriptObject evaluateWebScript:@"MyApp.consoleLog_('Test');"];
}
注入JavaScript時,上面的代碼有效( evaluateWebScript )
這是控制台輸出的內容:
2012-12-06 08:03:05.605 BetterDesktop[8669:303] Did finnish load...
2012-12-06 08:03:05.605 BetterDesktop[8669:303] Object: undefined
2012-12-06 08:03:05.606 BetterDesktop[8669:303] Object: <WidgetsDelegate: 0x10133de60>
2012-12-06 08:03:05.607 BetterDesktop[8669:303] JSLog: Test
該命令有效,但是當我使用頁面時它不起作用。
<html>
<head>
<script type="text/javascript">
if (typeof(MyApp) != "undefined"){
document.write('<br/><h1>hi</h1>');
MyApp.consoleLog_('Test from HTML');
}
else{
document.write('<br/><h1>Not Defined</h1>');
}
</script>
</head>
<body>
</body>
</html>
它認為“MyApp”未定義,有什么建議嗎?
(順便說一句,WebView沒有連接到這個類,它只是委托)
您應該從-webView:didClearWindowObject:forFrame:
WebFrameLoadDelegate
方法而不是-webView:didFinishLoadForFrame:
對象注入WebView。 在調用didClearWindowObject
之前,不保證window
對象已正確初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.