UIWebView doesn't load external JavaScript file
Asked Answered
B

4

27

I have the following innocent-looking code (index.html), but it doesn't load the code.js file. It works well if I copy/paste the contents of the file in the HTML page. Both index.html and code.js files are in the same directory.

index.html:

<html>
<head>
<script type="text/javascript" src="code.js"></script>
</head> 
<body onload="drawImage()">
  <div><canvas id="canvas" width="320" height="480"></canvas></div> 
</body>
</html>

ViewController.m:

- (void)viewDidLoad {
  [super viewDidLoad];
// load the first webpage
[homePageWebView loadRequest:[NSURLRequest requestWithURL:[NSURLfileURLWithPath:
  [[NSBundle mainBundle] pathForResource:@"index"ofType:@"html"] isDirectory:NO]]];
}
Blodget answered 31/8, 2010 at 5:30 Comment(0)
A
59

I have found that Xcode thinks that the js file needs to be compiled.

Open the project in Xcode. Go to "Targets" and look in "Compile Sources". If you see your js file in that folder, move it to the "Copy Bundle Resources" folder and delete it from the "Compile Sources" folder.

Delete the app from your iPhone if it is installed already for testing. Go to the Build menu in Xcode and Clean all Targets. Then recompile.

Check now to see if your HTML file actually sees your js file now.

Linda

Alys answered 2/9, 2010 at 17:13 Comment(12)
And where does one find "Targets" in Xcode? I'm running the latest version doing ipad dev and there is no such named screen....Protection
oh wait i found it. It's a bucket on the left hand sideProtection
ehm... if you found your answer. Please close the question :)Gladiate
well done linda. I think just to clarify for those of us that don't use xcode much. Targets is on the left in the tree menu. It has a picture of a red and white arrow board or dart board. when you click to open it, it expands like hitting the arrow on a folder in mac's FINDERProtection
Thats awesome...That wasn't obvious at all. Jason you need to look under the tab "Build Phases" when you are on Targets.Rhombic
I cant get it to work with the js files located in a subfolder. Only works when the js files is in the same folder as the html file :/Rhombic
Unless i clean and build the project...every time when making changes to a js fileRhombic
To be precise: Click on your project in the project navigator on the left. The main pane should now have a sidepane on the left. This sidepane should have "PROJECT" and "TARGETS". Click on you project under the "TARGETS" heading. The pane to the right should now have a bunch of tab headings going "Summary", "Info"... etc. Click on "Build Phases". This should then show a bunch of subsections. Open up the sections "Compile Sources" and "Copy Bundle Resources." Then, click and drag ALL the javascript files from the "Compile Sources" section to the "Copy Bundle Resources" section.Cadmium
Just a small "correction" xcode will not compile the javascript. It will embedded it into myIpaApp.ipa/myJavaScript.jsEpilate
I love you @Linda!. I have been fighting this for ages. This was driving me crazy. Thanks to @Rhombic too. I can't make it work within a subdirectory neither but it doesn't mind. I'm happy :)Subtonic
I worked for me. I still wonder though why it has moved my .js as a file to compiled this time (it was in the copy before).Mealworm
Is there any chance we can do this without XCode ? I am working with Ionic , cordova AND I would Like to include external scrips like Stripe in the headerHarbard
P
7

You need to read the html file into a string and set the baseURL when loading so relative paths can be understood.

NSError* error;
NSString* html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] encoding:NSASCIIStringEncoding error:&error];

[webview loadHTMLString:html baseURL:[self getBaseURL]];

- (NSURL*) getBaseURL {
    NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSRange r = [path rangeOfString:@"/" options:NSBackwardsSearch];
    path = [path substringToIndex:r.location];

    path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
    path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    path = [NSString stringWithFormat:@"file:/%@//",path];
    return  [NSURL URLWithString:path];
}

Something like that should work for you.

Prier answered 31/8, 2010 at 5:37 Comment(8)
I think if you set base in the header of the HTML document, it will work too, and will not require any additional code.Gurnard
How do you set the base header for a local file. It tried by putting <base href="./"> and <base href="/"> in the <head>, but still doesnt work. Can you give me an example please.Blodget
How could you know what the base URL of the file is going to be ahead of time? It would change depending on where it was deployed.Prier
oh so sorry, it wasnt clear above, all the files are in the resource bundle, and hence local to the app.Blodget
This should not be needed. Loading a local file:// url will work fine.Alexina
'file://' doesn't work squeegy. My JS file is located in my resources folder. neither does the code that skorulis sent throughProtection
Using this getBaseURL function worked a treat for me! All files are in the resources folder but js and images weren't showing up until I got the base URL correct. Thanks @skorulis!Extrauterine
Why use pathForResource instead of URLForResource?Metzler
L
6

To supplement Linda's Answer here is where you find the files:

enter image description here

Localism answered 2/11, 2012 at 8:49 Comment(0)
L
5

I also faced the same problem: I overcame it by doing the simple thing when adding the files to XCode I did a small change that is shown in the figure below:

In the figure below, one is for adding HTML, Javascript and CSS like files and the second is for general XCode files.

for HTML, Javascript and CSS files

For general XCode files

Lassie answered 2/7, 2012 at 10:44 Comment(1)
Simple and effective solution :)Vitriform

© 2022 - 2024 — McMap. All rights reserved.