Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to embed a local web server into phonegap project?

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?

like image 619
Vong Tình Avatar asked Jul 25 '14 15:07

Vong Tình


Video Answer


2 Answers

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.

like image 127
Michael Avatar answered Sep 18 '22 11:09

Michael


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.requestId,
                      {
                          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

like image 39
Michael Bykovski Avatar answered Sep 21 '22 11:09

Michael Bykovski