简体   繁体   中英

Objective-C/Cocoa windowScriptObject commands not working from loaded page

I am trying to get a 'windowScriptObject' working, this is my Objective-C code below:

- (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');"]; 
}

The above code works when I inject JavaScript ( evaluateWebScript )

This sis what the console out put is:

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

The command works, however when I use a page it doesn't work.

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

It believes that 'MyApp' is undefined, any suggestions?

(By the way, the WebView is not connected to this class, it is just the delegate)

You should inject your objects in to the WebView from within the -webView:didClearWindowObject:forFrame: WebFrameLoadDelegate method rather than within -webView:didFinishLoadForFrame: . The window object is not guaranteed to have been correctly initialized until didClearWindowObject is called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM