zyguan
3/20/2017 - 4:41 PM

ivoc.user.js

// ==UserScript==
// @name         iVoc
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  save your search history on bing/dict!
// @author       zyguan
// @match        https://cn.bing.com/dict*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @grant        GM_addStyle
// ==/UserScript==

GM_addStyle(`
img.ivoc-btn-icon {
  opacity: .6;
}
img.ivoc-btn-icon:hover {
  opacity: 1;
}
`);

(function() {
    'use strict';
    const ICO_URL_DEL = 'https://cdn1.iconfinder.com/data/icons/freeline/32/Delete_discart_exit_less_line_minus_negative_no_premium_remove-24.png';
    const ICO_URL_DOWN = 'https://cdn1.iconfinder.com/data/icons/freeline/32/Download_save_down-24.png';

    var getWord = function() {
        var $w = document.querySelector('#headword');
        return $w ? $w.textContent : null;
    };

    var isEnglishWord = function(w) {
        return typeof w === "string" && !!w.match(/^[0-9a-zA-Z ]+$/);
    };

    // remove word from the vocabulary
    var w = getWord();
    if (isEnglishWord(w)) {
        GM_setValue(w, GM_getValue(w, 0)+1);

        var $del_parent = document.querySelector('#headword h1');
        var $del_icon = document.createElement('img');
        var $del = document.createElement('a');
        $del.style.float = 'right';
        $del_icon.src = ICO_URL_DEL;
        $del_icon.classList.add("ivoc-btn-icon");
        $del.addEventListener('click', function() {
            GM_deleteValue(w);
            $del_parent.removeChild($del);
            $del_parent.innerHTML = `<del>${w}</del>`;
            $del_parent.style.color = 'gray';
        });

        $del.appendChild($del_icon);
        $del_parent.appendChild($del);
    }

    // download the vocabulary
    var $down_parent = document.querySelector('#id_h');
    var $down_icon = document.createElement('img');
    var $down = document.createElement('a');
    $down_icon.src = ICO_URL_DOWN;
    $down_icon.classList.add("ivoc-btn-icon");
    $down_icon.style.verticalAlign = 'text-bottom';
    $down.download = 'vocabulary.csv';
    $down.addEventListener('click', function() {
        var csv = GM_listValues().map(function(w) {
            return `${w},${GM_getValue(w)}`;
        }).join("\n");
        $down.href = "data:text/csv;base64," + btoa(csv);
    });

    $down.appendChild($down_icon);
    $down_parent.appendChild($down);

})();