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

好久不见. 提交于 2019-12-03 00:32:35

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.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!