idealy / PX-file download for PX-Web

// ==UserScript==
// @name        PX-file download for PX-Web
// @namespace   http://www.stat.fi/
// @description Add links to download PC-Axis files from PX-Web.
// @include     http://pxnet2.stat.fi/PXWeb/pxweb/*
// @include     https://pxnet2.stat.fi/PXWeb/pxweb/*
// @version     0.2.1
// @grant       none
// @license     MIT
// @author      Daniel Davis (idealy)
// ==/UserScript==

/*
 * Adds download links that were removed from PX-Web in an update in 2017.
 * Works with StatFin, not guaranteed to work with other PX-Web sites.
 */

(function () {
  'use strict';
  function main() {
    var leaves = document.getElementsByClassName('AspNet-TreeView-Leaf');
    if (leaves.length > 0) {
      Array.from(leaves).forEach((leaf) => {
        if (leaf.getElementsByClassName('PX-Download-Link').length === 0) {
          let href = leaf.getElementsByTagName('a')[0].getAttribute('href');
          //console.log(href);
          let s = href.split('__');
          let s0 = s[0].split('/');
          let s2 = s[2].split('/');
          if (s2[1].length > 0) {
            let url = '/database/' + s0[s0.length - 1] + '/' + s[1] + '/' + s2[0] + '/' + s2[1];
            //console.log(url);
            let a = document.createElement('a');
            a.setAttribute('class', 'PX-Download-Link');
            a.setAttribute('href', url);
            a.appendChild(document.createTextNode('[Download .PX file]'));
            leaf.appendChild(a);
          }
        }
      });
    }
  }
  window.setInterval(main, 1000);
}) ();