Youtube: I'm feeling lucky

Add I'm feeling lucky button to Youtube

当前为 2015-11-05 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Youtube: I'm feeling lucky
// @namespace    http://tampermonkey.net/
// @version      1.0.2
// @description  Add I'm feeling lucky button to Youtube
// @author       divide100
// @match        http*://www.youtube.com/*
// @grant        GM_openInTab
// @require https://greasyfork.org/scripts/5679-wait-for-elements/code/Wait%20For%20Elements.js?version=46106
// ==/UserScript==
/* jshint -W097 */
'use strict';

var util = {
    log: function () {
        var args = [].slice.call(arguments);
        args.unshift('%c' + SCRIPT_NAME + ':', 'font-weight: bold;color: purple;');
        console.log.apply(console, args);
    },
    q: function(query, context) {
        return (context || document).querySelector(query);
    },
    qq: function(query, context) {
        return [].slice.call((context || document).querySelectorAll(query));
    },
    xmlReq: function(url, cb){
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'document';
        xhr.onload = cb;
        xhr.send();
    }
};

var SCRIPT_NAME = "Youtube's feeling lucky";
var SEARCH_SEL = '#masthead-search';

util.log('Starting');

waitForElems(SEARCH_SEL, function(searchBar) {
    var btn = util.q('button', searchBar).cloneNode(true);
    var searchCrit = util.q('input', searchBar);
    btn.childNodes[0].textContent = 'Feelin\' Lucky';
    btn.childNodes[0].className = '';
    btn.onmousedown = function(e) {
        if(e.button === 1) {
            e.preventDefault();
        }
    }
    btn.onclick = function(e) {
        e.preventDefault();
        var strCrit = searchCrit.value;
        if(strCrit) {
            util.xmlReq('https://www.youtube.com/results?search_query=' + strCrit.split(' ').join('+'), function(xhe) {
                if(e.button === 1) {
                    GM_openInTab(util.q('.item-section a', xhe.target.response.body).href, false);
                }
                else {
                    window.location.href = util.q('.item-section a', xhe.target.response.body);
                }
            });
        }
        return false;
    };
    //util.log(btn);
    searchBar.insertBefore(btn, searchBar.firstChild);
});