Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  115] [ 5]  / answers: 1 / hits: 15513  / 15 Years ago, sun, july 12, 2009, 12:00:00

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


More From » objective-c

 Answers
107

You don't have to do anything to enable JavaScript; it's enabled in the WebView by 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 baseURL you're specifying is correct (since in the html file you're referring to jquery.js with a relative URL using just the filename) and that you've included the jquery.js file into the bundle resources.



The code you posted will result in a nil value for the url variable: +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 where index.html and jquery.js reside, which you can get by removing the filename from the path you've got (using NSString's -stringByDeletingLastPathComponent:). Here's how you get the correct baseURL:



NSURL *url = [NSURL fileURLWithPath:[filePath stringByDeletingLastPathComponent]];

[#99144] Tuesday, July 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dezmondhumbertob

Total Points: 79
Total Questions: 112
Total Answers: 107

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;