I need to build an offline Phonegap app. However, all of my js functions need a web server to run well. Is it possible to embed a local web server into phpnegap project?
问题:
回答1:
Yes, it's possible using a Cordova HTTPD plugin:
https://github.com/floatinghotpot/cordova-httpd
I haven't used it yet, but I may need to with my current project.
One drawback is that if the IP address is known, others will be able to browse the hosted files. Before I deploy, I'll be changing that behavior.
回答2:
Now it is possible, I created a plugin what meets your requirements.
First install it via:
cordova plugin add https://github.com/bykof/cordova-plugin-webserver
Then just describe your Webserver in the start of your application
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
</head>
<body>
<script>
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
webserver.onRequest(
function(request) {
console.log("This is the request: ", request);
webserver.sendResponse(
request.responseId,
{
status: 200,
body: '<html>Hello World</html>',
headers: {
'Content-Type': 'text/html'
}
}
);
}
);
// Starts webserver with default port 8080
webserver.start();
//... after a long long time
// stop the server
webserver.stop();
}
</script>
</head>
</html>
after that you can access your webserver on another browser in your network: http://<ip-of-webserver-device-in-local-network>:8080
Reference: https://github.com/bykof/cordova-plugin-webserver
回答3:
An embedded webserver is possible, and in the (distant) past, Cordova Android even had one.
However, for the general use case it should not be needed. If you must serve files from a local server, see Michaels answer.
loadUrl through the native webview api is NOT the (best) to include javascript in the webview's runtime.
By default, there is no reason why you need to interact natively with the webview in the first place.
Instead, create an index.html and include the javascript you want through tags, as @frank describes
The cordovawebview.loadURL will by default load index.html, and does not need to be modified.
look at the www/index.html in the Cordova Hello World App for a simple example.
--edit-- link to index.html in CDV Hello World