Add missing functions to HtmlUnit: Vue.js case


Depending the application you work on HtmlUnit can miss few functions. If you open the javascript engine you will quickly see it is quite complex to extend from your code and can be annoying when sometimes it just misses few methods!

Let see with the case of Vue.js how to fix it very easily.

First the error. If you run a Vue.js application with HtmlUnit 2.19 you will get these errors:

net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Impossible de trouver la fonction hasAttributes dans lobjet {1}. (http://localhost:50520/app/js/vue/vue.min.js#6)

So seems hasAttributes can’t be found in HtmlUnit. Checking in vue.min.js at the related line you can quickly identify it is the Node.prototype.hasAttributes function which is missing.
This function is however trivial: it returns true if the node has some attribute false otherwise. Attributes being something pretty important for the DOM HtmlUnit already implements them, in particular the getter so implementing hasAttributes is as easy as checking the length of this attribute.

How to do so? Well on java side it is quite hard to inject your code so let’s monkey patch on js side. The trick is to be able to inject some javascript. In my case I had an index.html dedicated for testing purpose so a simple script block was enough:

<html>
<body>

<div id="content">
    <router-view></router-view>
</div>

<script>
    // here is the magic
    // hack for HtmlUnit
    Node.prototype.hasAttributes = function() {
        return this.attributes && this.attributes.length > 0;
    };
</script>

<script src="js/lib/requirejs/require.min.js"></script>
<script>
    // standard application boot
    require.config({ baseUrl: '/app/js/app', paths: { 'Vue': '../lib/vue/vue.min' } });
    require(['Vue', 'boot'], function (Vue, Boot) { Boot(); });
</script>

</body>
</html>

Of course you can just create a htmlunit-hack.js and import it in your index.html but the message of this post is: it is not because HtmlUnit misses few functions that you should abandon it. Some of them are trivial to fix and HtmlUnit avoids to have to rely on PhantomJS which hangs quite easily or NodeJS tooling which is not yet perfectly integrated with all platforms or build tools.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s