2012-12-05 36 views
1
加載頁面

我試圖得到一個「windowScriptObject」工作的工作,這是我下面的Objective-C代碼:的Objective-C /可可windowScriptObject命令不

- (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

這SIS什麼控制檯放出來是:

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的' 是不確定的,有什麼建議?

(順便說一句,web視圖沒有連接到這個類,它只是委託)

+0

好的,所以我發現如果我在'onclick'方法中運行代碼,它工作正常。 –

回答

4

您應該從-webView:didClearWindowObject:forFrame:WebFrameLoadDelegate方法中,而不是在-webView:didFinishLoadForFrame:注入你的對象到的WebView。不保證window對象被正確初始化,直到調用didClearWindowObject

+0

感謝您的幫助。 –