I have a very simple Mac Cocoa app that just has a Web View that loads an HTML file with some CSS and JavaScript. I have hooked up the app delegate to this method:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSString* filePath = [[NSBundle mainBundle] pathForResource: @"index" ofType: @"html"];
NSURL *url = [NSURL URLWithString: filePath];
[[self.webView mainFrame] loadHTMLString: [NSString stringWithContentsOfFile: filePath] baseURL: url];
}
The index.html file contains the following:
<html>
<head>
<title>Hello, World!</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(function($){
$('h1').fadeOut()
})
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The style.css file gets loaded correctly, because I set the background to grey in that, so I know it can load other assets from the resource bundle. The javascript code does not get executed. If I open index.html in Safari, the Hello World h1 disappears, as expected. Why doesn’t this happen in the app in my WebView? Do I have to do something to enable JavaScript? The box next to JavaScript is checked in Interface Builder.
The code for this is available at http://github.com/pjb3/WebViewApp
You don’t have to do anything to enable JavaScript; it’s enabled in the
WebViewby default. And like you said, you can always check in Interface Builder that the JavaScript checkbox is selected.What you have to do, though, is make sure that the
baseURLyou’re specifying is correct (since in the html file you’re referring tojquery.jswith a relative URL using just the filename) and that you’ve included thejquery.jsfile into the bundle resources.The code you posted will result in a
nilvalue for theurlvariable:+URLWithString:expects a valid URL string (that conforms to RFC 2396) as the argument (which the filesystem path you’re providing is not). What you want is+fileURLWithPath:, and you also need to use the filesystem path of the directory whereindex.htmlandjquery.jsreside, which you can get by removing the filename from the path you’ve got (usingNSString‘s-stringByDeletingLastPathComponent:). Here’s how you get the correctbaseURL: