Tom Kincaid
Tom Kincaid

Reputation: 4975

How to include a local script in remote html file in Cordova / Phonegap?

I have an iOS Cordova/Phonegap project which loads html pages from the internet. This works if I upload cordova.js and all the plugins then include cordova.js in the html page. However, since the files are already in the app, it seems a waste to make people download them all. I'm trying to include the local files in the remote html, but it doesn't seem to load. How can I do this?

I have a local script test.js in www

alert("test");

I'm getting the path to it with

[[NSBundle mainBundle] pathForResource:@"test" ofType:@"js" inDirectory:@"www"];

It looks something like

/var/containers/Bundle/Application/E31EA51E-7ED0-4D30-90FC-57ACBF3B3DA5/MyApp.app/www/test.js

I include the file in the remote html

<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' gap://ready file: data:">
<script src="file:///var/containers/Bundle/Application/E31EA51E-7ED0-4D30-90FC-57ACBF3B3DA5/MyApp.app/www/test.js" type="text/javascript"></script>

However, the script never loads.

Edit: I added "Access-Control-Allow-Origin: *" header to the http page, but it still doesn't work.

Upvotes: 1

Views: 1406

Answers (3)

Guy L.
Guy L.

Reputation: 163

This can be done using a PR to the file plugin which solves the mixed content problem on ios: apache/cordova-plugin-file#296 The fixed version is available at: https://github.com/guylando/cordova-plugin-file

If you load a remote site https://example.com on the webview then it allows to access local files using the url: https://example.com/cdvfile/bundle/www/cordova.js instead of cdvfile://localhost/bundle/www/cordova.js And by this solves the mixed content problems

Upvotes: 2

Sigma
Sigma

Reputation: 68

if you are using UIWebView, it's quite easy to go with a NSURLProtocol subclass which can intercept all of your network request and do your own job(in your case, accept the http://*/test.js and return the file content as the response).

However, if you are using the WKWebView, the NSURLProtocol would not work, and the latest WKURLSchemeHandler can't intercept the http/https requests either.probably set up an embedded http server is the way to go.

Upvotes: 1

syokensyo
syokensyo

Reputation: 173

Facing the same problem, I think using "WKURLSchemeHandler" to intercept ur request in iOS 11 will solve it.

Upvotes: 1

Related Questions