Using Polymer With Apache Cordova

Making great mobile applications used to require a certain type of skill, but with the latest technologies you don’t need much more than basic web design knowledge.  With the aid of Apache Cordova, developers can make native API calls directly from JavaScript functions.  Pair this with a front-end framework like Adobe PhoneGap or my current favorite, IonicFramework, and you can create stunning mobile applications with no more than CSS and HTML skills.

However, I recently discovered Polymer, a project by Google, and it looks pretty slick.  The best part is you can easily use Polymer with Apache Cordova to create a native mobile application.

To make a native Android application using Polymer and Cordova, you must first be aware that it will work best with Android 4.4 and higher.  For whatever reason, earlier versions of Android may produce questionable results when rendering the CSS that Polymer requires.

Let’s first create a Cordova project.  If you already have NodeJS and Cordova installed, great.  If not, install them and proceed by running the following commands to create an Android project:

When using Polymer in general it is recommended to use Bower as it will handle all the many dependencies required.  With NodeJS installed run the following from the command line to install Bower:

When Bower is installed, navigate to the www directory of your Cordova test project and initialize it to use Bower:

Answer all the Bower initialization questions to the best of your ability and you’ll be left with a bower.json file in your www root.  Our next goal is to download the Polymer components we plan to use and all their dependencies.  From the command line run:

Now for the fun part.  For the simplicity of this example we aren’t going to have much functionality.  The goal here is to create a Polymer application that makes use of the scaffold, cards, floating action button, and toast notifications all on an Android device.

All of the Bower installs should have ended up in a directory called bower_components and if you’ve done everything right up to this point, that directory should be in the www directory of your Cordova project.  In your index.html file replace all code with the following:

You’ll notice most of the code is Polymer while a few lines are related to the existing Cordova project.  All of the Polymer code found in this example was created with the Polymer Designer.

Let’s test this project so far in a web browser.  Using a command prompt, navigate to TestProject/www and run the following command:

When navigating to http://localhost:8000 you should see a page that looks like this:

Polymer Desktop

In the root of TestProject, run the following command to build your project for Android:

After installing to your Android device, you should have a fully responsive Polymer application that uses material design like Android L.

On my Nexus 5, the example looks like this:

Polymer Android

 

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • antonio

    hi!
    nice tut, though it seems to work only with latest versions of Android (JB not included). Am I right?

    I tried to apply your code on my Cordova app and run it on my smartphone (JB 4.2.1) and it doesn’t work… any suggestions?

    Thank you.

    • The Polymer libraries only work with the latest version of Chromium found in Android 4.4 and higher. I managed to get a few things working with earlier versions of Android, but it worked without problems in 4.4

      https://material.angularjs.org/

      The Material AngularJS library is meant to offer better support for older versions, but true Polymer at this moment in time works best with 4.4+.

      Hopefully that helps.

      Cheers,

    • You can use Crosswalk to get the latest version of Chrome onto any (2.3+) version of Android.

  • Stuart Rackham

    Excellent tutorial, worked through it and everything worked! Thank you.

    • I’m glad you got it working! Please be sure to share this post with anyone you think would get benefit from it.

      Cheers,

  • Ash

    I have just started using Cordova and Polymer. However, I am having problems navigating between pages. A simple anchor tag with href doesnt work. On my browser it does, but when I package it using CCA, and launch the app on my Android device, the links don’t work. Is it even possible to have multiple html files in the www folder?

    • Hi Ash,

      Do you happen to have any code you can share on Github? Might give everyone a better idea of your structure.

      Cheers,

  • Andy J T

    Great article! Thank you.

  • Bruno Rodrigues

    Thanks man you save my project !

  • Kenneth

    Hi,
    What does the performance feel like with polymer on the device? That is also the issue with Cordova apps I think.
    Thanks for the post!

    • Hi Kenneth,

      If you add Crosswalk to your build you should see a significant performance boost since it uses a better web runtime.

      I don’t notice any problems with my 4.4.4 device and Crosswalk will use the same runtime.

      • phil

        Hi Nic,

        Great tutorial, but could you please elaborate a bit on…..
        “If you add Crosswalk to your build”
        is this as easy as adding a line of script?

        Regards

        Phil

        • Hi Phil,

          Take a look at this other post I did on the topic of Crosswalk:

          https://www.thepolyglotdeveloper.com/2014/10/use-crosswalk-ionic-framework-android-apps/

          Yes, the post is targeted at Ionic Framework, but it should be exactly the same for any baseline Apache Cordova application. One of my readers made a script and posted it in the comments. However, use this readers script with caution if you go that route. I believe it does delete files without warning to get the job done.

          Let me know if you have further questions.

          Regards,

  • Nic, thank you, you saved me so much time. This is working nicely on the Cordova iOS emulator. Now I’m going to work on integrating InAppBrowser…..

    • No problem! Good luck with the InAppBrowser 🙂

  • Nikhil Verma

    Hey its good , but I wanna how Will be able to respond to events (button click and others as opening activity,fragment )and Others in this app , Is purely gonna be coded in web languages ?

    • Hi Nikhil,

      Apache Cordova is used for making hybrid mobile applications with HTML and JavaScript. It is an alternative to using Java and the standard Android life cycle.

      Google Polymer can take advantage of Apache Cordova’s APIs and respond to events such as clicks, pause, resume, ect.

      It is just a different approach to application development. If you want to stay strictly Java Android, I suggest you look at Android’s Material Design APIs for OS 5.0.

      Regards,

      • Nikhil Verma

        Ok Thanks . I am not able to get the page work . Its Just Displaying “It works”(if I am Using xampp local host) on blank page . I can’nt execute :
        python -m SimpleHTTPServer

        in my GitBash , its saying python not found.

        • Hi Nikhil,

          If you’re using Windows, Python is not installed by default. If you wish to use a Python local server on Windows you must first install it.

          I am not too familiar with XAMPP, so I don’t have all the answers on this one. By displaying “It Works” probably means it is serving the incorrect directory. I suggest you read the XAMPP manual and determine where your Apache Cordova files need to be.

          Regards,

  • Adam Schnaare

    Thanks so very much for the walkthrough. However I am having the hardest time with the end result. Everything works in my browser, but not on my Nexus 5 device or emulation. I get three errors consistently.
    Cannot call method ‘querySelector’ of null (index.js)
    Element name could not be inferred (polymer.js)
    Cannot call method ‘resolveUrlsInStyle’ of undefined (boot.js) – I think this is from polymer as well.

    Any help would be much appreciated.

    • Hi Adam,

      Would you mind posting your code to GitHub?

      I’d be happy to take a look at it. The problem could be as simple as a typo and it doesn’t hurt to have a second pair of eyes on it.

      Regards,

      • Adam Schnaare

        Here’s a gist of the index.html, bower.json, and config.xml just in case:
        https://gist.github.com/adamschnaare/a8b179b80a6d9852947e

        • Hi Adam,

          A few things caught my eye in your code.

          What is the following line?:

          The above looks like no script I’ve ever heard of.

          I also couldn’t find the following line in your code:

          I could be wrong, but I think correcting those two items will solve your problems. If not, we can continue to debug.

          Regards,

          • Adam Schnaare

            Yeah, I noticed that right as I posted it. I fixed it in the gist. That was a copy paste error to github, it was platform/platform.js while the code was running. Still no luck.

          • Hi Adam,

            Sadly it looks like one of the instructions in my post is already depreciated. See the following:

            https://www.polymer-project.org/docs/start/platform.html

            It says no longer to use:

            Instead you need to have Bower install the following:

            Once installed you can replace the platform.js line with this:

            It is also a good idea to remove the following from your index.js file if you haven’t already (elements don’t exist in your index.html):

            Let me know if that works for you.

            Regards,

  • Adam Schnaare

    Awesome! Thank you so much for the help. It is working and working well. I was racking my brain on what in the world I was doing wrong. I updated the gist at https://gist.github.com/adamschnaare/a8b179b80a6d9852947e for anyone that wants to reference.

    • Excellent! I’ve updated the tutorial to reflect the new setup instructions.

      Regards,

      • Koen Hendriks

        I’m having this problem as well, even after using the newly gist Adam shared. any ideas?

        • The tutorial has since been updated after Adam pointed it out. If following it, there shouldn’t be any issues.

          Mind giving more details of your set up? For example:

          1. What version of Android are you using?
          2. What errors are you receiving in the ADB logs?
          3. What version of Apache Cordova are you using?

          It also wouldn’t hurt to see your source code. Mind making Gist or uploading to GitHub for everyone to take a look at?

          Regards,

          • Koen Hendriks

            Hey Nic,

            I removed it from github, but here it is again.
            https://github.com/koenhendriks/material/

            live:
            http://koenhendriks.com/material/

            Im also getting the query selector error

            Uncaught TypeError: Cannot read property ‘querySelector’ of null

            in index.js on line 41

          • Hi Koen Hendriks,

            Take a look at line 41 to 45 in your index.js. You still have JavaScript references to HTML elements that don’t exist anymore, thus the objects are ‘null’.

            I suggest you remove those lines from your code and try again.

            Regards,

          • Koen Hendriks

            Hmm yes i see…
            I removed the files. I have no more errors in my console but it still won’t show up right on my phone when build with cordova.
            see this screenshot.

            http://i.imgur.com/gPA6VOA.png

          • Koen Hendriks

            I just tested this one my Nexus 7, and it works fine… any ideas why it won’t work on my HTC Sensation ?

          • What version of Android is your HTC Sensation? The tutorial works best with 4.4 or higher because starting with 4.4 Android ships with Chromium. I’m not saying it won’t work with lower, but I am sure it won’t work well. Chromium understands more of the custom new Polymer tags.

            Regards,

          • Koen Hendriks

            Yeah I figured something like that. I’m running my HTC on 4.1 so i guess that would be the case.

          • Brad Martin

            Same issue rendering on a Samsung Galaxy S5 with latest update. I think it’s 4.3

          • Yea, the older Android versions have ancient browsers bundled into them. You need at least 4.4 to run it properly. If you wanted a work around, adding Crosswalk to your project should work:

            https://www.thepolyglotdeveloper.com/2014/10/use-crosswalk-ionic-framework-android-apps/

            Regards,

          • Brad Martin

            Thanks Nic, I’ll follow that guide you have later and see what happens. Do you know if you can build the distributable packages using Phonegap Build utilizing Crosswalk?

          • I am anti Phonegap Build or any cloud based building solution. They tend to be nothing but headache for complex applications.

            With that said, I have no idea if it works for Crosswalk. If you spend time on it and it works, please report back for others who might use a cloud building solution.

            Regards,

          • Brad Martin

            Okay, I’m having no luck as of now and can’t find any documentation on the matter so I’m going to lean towards it not being supported. Do you have any articles/tutorials/links for configuring an environment (Windows) to build locally with the command line? I have always used phonegap build so I need a good starting point for setting up my environment.

          • You now have the correct attitude :-).

            I am a Mac and Ubuntu Linux user myself, so I won’t be the best help when it comes to configuring Windows. However, I don’t think it is too difficult.

            Download the latest Android SDK and run the installer:

            http://dl.google.com/android/installer_r24.0.2-windows.exe

            Then download the latest NodeJS and run the installer:

            http://nodejs.org/download/

            From the command line, run npm install -g cordova. At this point, I think you just cross your fingers and hope my Cordova tutorials work. (again not a Windows user).

            If you decide to take a leap and start using Ubuntu, I’ve crafted a self installing script to do everything for you:

            https://www.thepolyglotdeveloper.com/2014/09/install-android-cordova-ionic-framework-ubuntu/

            Regards,

          • Brad Martin

            Wow Nic, after a full day of nothing but trouble configuring the windows pc I finally have the app running with Crosswalk on the S5 with Polymer. Calling it a day now. Thanks for the tutorial. I had several issues with setting the PATH values on the PC. Particularly with JAVA, you can’t use a user variable for the path you have to enter the entire path into the PATH value. Then it was a matter of installing Android 19 SDK tools for the builds. After that, the rest is easy. Thanks again for the great blog posts.

          • Glad you got it working! Sorry I couldn’t ease your pain. Microsoft Windows is just out of my realm of knowledge if you can believe that.

            Regards,

          • You must be getting errors with ‘adb logcat’. Can you update your GitHub repository and include a file in the repository that has your log?

            Regards,

  • Is it possible to export existing app in Apache Cordova? Thanks ASAP! 🙂

    • You have to integrate all your web application files into your Apache Cordova project.

      • I already integrated all of my webapp but the problem now is, it is running in the emulator but in the real device it only shows the white screen.

        • What is the Android version of your emulator and what is the Android version of your device?

          • Android 4.4 on emulator and also the device

          • What do the logs say? I’m talking device logs with adb logcat.

          • It doesn’t have the errors. We’re running your sample app on our phones, it’s running properly.

          • The app that is misbehaving should have errors in the logs. If you can’t find them would you mind putting your project on GitHub so everyone who follows this post can take a look?

          • I’ll just check

  • Paresh

    Thanks nice tutorial.
    I created project successfully but when i run project for android graphics and navigation goes down.
    Please see this http://prntscr.com/5rgaj8

    • What do the logs say? If it isn’t rendering correctly, there will be logs.

      Regards,

      • Paresh

        Thanks. Sorry but where i can file log in my project?

        • Please follow this guide if you’re unfamiliar with ADB:

          https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

          Regards,

          • Paresh

            I can run adb install -r platforms/android/ant-build/CordovaApp-debug.apk successfully and apk successfully install on device i mean in genymotion but design not appears.

          • Yes but I need to know your logs. Please use the link I gave you to get them. Without your logs I cannot help you.

            Regards,

          • Paresh

            My command prompt display following log

            http://notepad.cc/adblog

            Thanks

          • I see a few problems in your logs.

            First, I see the following:

            You have JavaScript code that is throwing errors. You need to fix that.

            Another error I see is as follows:

            My assumption is you are trying to test this on an Android version less than 4.4.4. Is this correct?

          • Paresh

            Yes you are right. I am run on 4.1.1 in genymotion. Need to run on android 5?

          • As quoted from this article:

            “To make a native Android application using Polymer and Cordova, you must first be aware that it will work best with Android 4.4 and higher. For whatever reason, earlier versions of Android may produce questionable results when rendering the CSS that Polymer requires.”

            You need a web runtime that supports what Polymer offers. If you wish to support lower versions, you need to install Crosswalk.

            Regards,

          • Paresh

            Thank you very much for valuable time

  • Peter Frazier

    i’m a bit stumped.. i’m guessing here, but i take it you can’t use the Polymer(‘element-name’, {}); for wiring up your app..

    i was happily going along and when i put the entire polymer portion of my app into its own element so i could use the internal wiring it broke the whole thing. shows up on the server but when i push to android phone i get blank page..

    • What do the error logs say when you’re on the device or simulator?

      Regards,

  • Hey there! First off thanks for taking the time out to make a blog post. I tried out your sample app and am surprised by how smooth the port is. I am quite new at this so sorry if something seems off. I already have a web app bult with Polymer and followed your tutorial for it but for some reason all it shows me is a white screen. I was reading up on it and some people say its due to the HTML imports. Is it? How would I fix it?
    Thanks again!

    Heres the live version of the app: thecoolstuffonline.com
    Here’s the code: https://github.com/najubhai/ticketsystem

    • The browser runtime needs to be able to understand the HTML imports. Mobile runtimes are a lot further behind than PC.

      What Android version are you testing on? Also what do your error logs say?

      Regards,

  • Brian from Indiana

    Thank you so much for this excellent tutorial. I was able to follow it and it worked first time! Of course life has both good news and bad, and my bad news is that I am trying to do something that would seem simple, but can’t get it to work.

    What I’m trying to do is patch in one of the various snippets from the “Polymer in 10 minutes” tutorial on the Polymer site. I have implemented all of the little snippets from the tutorial and they all work perfectly in a browser. But when I run the same app on my Android phone, I get all of your app, but my added stuff doesn’t show up at all.

    As a simple e.g. I put in this import in the head section

    And then, inside your core-card element, I snuck in the snippet to render the element:

    It renders just fine in a browser with this element (or any other from the tutorial coded similarly), and I installed the Ripple plugin in Chrome and it works fine there, too. But when I push it to the (4.4.4) device, I still only see your content and nothing of the piece I added.

    Any perspectives I could get on this would be much appreciated.

    • When it is installed on the device, if you check the logs with ADB, what do you see?

      https://www.thepolyglotdeveloper.com/2014/12/debugging-android-source-code-adb/

      Polymer errors are painful to find, but usually they will still show up. Lets start there though.

      Regards,

      • Brian from Indiana

        I could figure out a way to attach it, but I uploaded it to Google drive, and here is a link:

        https://drive.google.com/file/d/0B1w89i1eEo-SOEh4ZU51Z29lMzg/view?usp=sharing

        • You’re going to hate me for this, but I don’t test other people’s binary files.

          Can you add the null pointer exception to this comment? You may want to dig around and get ADB to recognize your device. It is an incredibly useful way to test.

          I find Polymer errors hard to find in the logs, but usually they are present.

          Regards,

          • Brian from Indiana

            The link is not to the app; it’s to the logcat file. I can’t find a way to attach it to a Disqus post, although I’m sure there must be a way.

          • Sorry I misunderstood. I thought you were having me test a binary. I opened your log and found this:

            It may not correct the problem, but you can’t know for sure until all your errors are fixed.

            Regards,

          • Brian from Indiana

            App runs perfectly fine in several versions of Chrome, plus it renders perfectly running on Ripple under Chrome. So it only does this on Android. . . . in other words, I have no crash to investigate, AND, it doesn’t crash under Android either; it just shows the things you wrote but not the element I added.

          • That is very weird then. I know this has a slim shot at working, but what if you bundled with Crosswalk? It is not exactly the same as the runtime that ships with 4.4.4 which is why I’m wondering if it would make any difference.

          • Brian from Indiana

            I have what smells like a clue. When I run the app in the browser, console is clean. When I run it in ripple, though; it complains that it can’t find config.xml and cordova.js. Kind of scratching my head though; I’m running the webserver with the DocumentRoot set to the cordova “www” directory, and it seems like that’s where it ought to be pointing, as it works perfectly. These errors only show up in Ripple, btw, not Chrome. I’m going make copies of those files inside the www space, and see what that does to the app. . . . I’ll keep you posted.

          • Please keep me posted.

          • Brian from Indiana

            My money right now is that Cordova is getting tripped up on some of the data binding-event stuff that’s baked into Polymer, and which I don’t think your code makes use of?

          • It is possible. Even with 4.4.4 and 5.0 devices, it may not be using the latest version of Chromium. If new web standards are introduced between versions, the devices may not recognize how to process them.

          • Guest

            I have what smells like a clue. When I run the app in the browser, console is clean. When I run it in ripple, though; it complains that it can’t find config.xml and cordova.js. Kind of scratching my head though; I’m running the webserver with the DocumentRoot set to the cordova “www” directory, and it seems like that’s where it ought to be pointing, as it works perfectly. These errors only show up in Ripple, btw, not Chrome. I’m going make copies of those files inside the www space, and see what that does to the app. . . .

  • Aneesh Sarkar

    Hey Nic,

    First thing great tutorial. I followed exactly what is put up. But I am getting error like following.

    Uncaught TypeError: prototype.registerCallback is not a functiondesugar @ polymer.html:37window.Polymer @ polymer.html:21(anonymous function) @ core-toolbar.html:91(anonymous function) @ core-toolbar.html:152

    Can you please see why this is coming?

    • It is possible that my tutorial is out of date. Polymer is a rapidly changing platform and I wrote this last year.

      Can you put your project on GitHub?

      Regards,

      • Tom Hemmes

        Did you find a solution to this problem already? Having the same problem here. Eager to get started with polymer, so also eager to help out here.

        Thanks in advance!

        • I didn’t get the information I needed. If you’re having problems, please list the errors and put your project on GitHub.

          Thanks,

          • Tom Hemmes

            I tried it again by initializing the polymer project outside the cordova www folder, manually copying it to the www folder and merging the index html. Now it seems to work, sorry for bothering you.

          • I’m glad you got it! You were not bothering me. I was just trying to get more information from the previous poster. Hard to troubleshoot a problem without all the information.

            Best,

  • Darwin Medina ⎝⏠⏝⏠⎠

    Apparently PhoneGaps does not support to import HTML <link rel = “import” .., so i used this ( https://github.com/polymer/vulcanize) resource to “vulcanize” the HTML , but always the app show the blank screen.
    Android Log: E/Web Console(6522): Uncaught ReferenceError: CustomEvent is not defined at file:///android_asset/www/bower_components/webcomponentsjs/webcomponents-lite.js:1327

  • python is not recognized as an internal and external command operable program or batch file that error is showing when i run that
    command
    python -m SimpleHTTPServer

    how to run them using local server like xampp

    • wener

      You should install python first.

  • Serg

    routes error when i’m switching tabs, i’m use starter kit, please someone tell me beautiful solution

    • Mind pasting your error logs? Hard to help without them.

      • Serg

        thank you already fix it, something was wrong with my polymer-element

  • Ryan Heimberger

    It works in firefox, but not in Chrome or Android 🙁

  • Lorenzo Volponi

    i set polymer and bower in the platform/android/www directory (maybe this is the error) and when serving with python i get some error and alert, should i put polymer and bower in the project_name/www directory? thank you

    • The platform/android/www directory is a build directory. You should be installing things to the development directory project_name/www.

      Regards,

  • Lorenzo Volponi

    i set polymer and bower in the platform/android/www directory (maybe this is the error) and when serving with python i get some error and alert, should i put polymer and bower in the project_name/www directory? thank you

  • Jaya Gautam

    very useful tutorial sir 🙂

  • alonso01cr

    Hey there, very useful your tutorial, I used it for starters on an app I am recently developing by using polymer on a Cordova app. I am quite new on Polymer, I have a problem when trying to navigate through pages and Polymer forces links to be in HTTP protocol instead of file protocol. So at this point I am unable to reference images or HTML URLs. Not sure if it’s a noob question but what would be the strategy in Cordova apps for emulating a HTTP server and being able to load correctly HTML and files?

    • Can you give me examples of what you’re referring to?

      • alonso01cr

        Hi Nic, sure! When I try to navigate to another page in my polymer web app inside cordova, let’s say, by using:

        window.location = ‘index.html’;

        Polymer complains saying that the file cannot be found, in a toast message saying:

        Can’t find: file://android_asset/www/index.html#!/android_asset/www/index.html. Redirected you to Home Page Ok

        Similar happens when trying to retrieve a local image inside my www folder.

        • That is strange. I’m not really sure why it’s doing that.

        • Grahen Kraken

          try using relative paths, but for navigation you should use iron-pages instead of changing the file you are viewing

  • Nil Gadiana

    Hi Nic, could you help me out? I’m really new to Polymer.
    When I run “bower install –save Polymer/core-elements”
    It says “Unable to find a suitable version for polymer, please choose one by typing one of the numbers below:”
    Same as “bower install –save Polymer/paper-elements”
    I hope you could help me out. I’ve attached some images.
    Thank you.

  • Nagesh Acharya

    Hey Nic Raboy,

    I have observed that in iOS 10, My app UI has broken. How to resolve that one ? Style are not coming properly.