ニコニコ動画で視聴終了後自動的に次の動画に移動

let.hatelabo.jp

// ==UserScript==
// @name         nico_auto_load
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.nicovideo.jp/watch/sm*
// @grant        none
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
// ==/UserScript==
var result3 = document.evaluate('//ul[@class="TagList"]', document, null, 7, null);
result3.snapshotItem(0).insertAdjacentHTML('beforeend', '<select id="auto_load"><option value="">位置</option><option value="1">1番目</option><option value="2">2番目</option></select>');
var result4 = document.evaluate('id("auto_load")', document, null, 7, null);
result4.snapshotItem(0).addEventListener('change', function () {
  var selectedValue = $("#auto_load").val();
  if (!('load_order' in localStorage) || Number(localStorage.getItem('load_order')) != selectedValue) {
    localStorage.setItem('load_order', selectedValue);
    alert("読み込む動画の位置をローカルストレージに書き込みました");
  }
});
var result = document.evaluate('//video', document, null, 7, null);
result.snapshotItem(0).addEventListener('ended', function () {
  if (Number(localStorage.getItem('load_order')) == 1) {
    //動画説明文の1番目にリンクがある場合
    var result2 = document.evaluate('//div[@class="VideoDescription-html"]/a[1][contains(@href,"watch/sm")]', document, null, 7, null);
    location.href = result2.snapshotItem(0).href;
  } else if (Number(localStorage.getItem('load_order')) == 2) {
    //動画説明文の2番目にリンクがある場合
    var result5 = document.evaluate('//div[@class="VideoDescription-html"]/a[2][contains(@href,"watch/sm")]', document, null, 7, null);
    location.href = result5.snapshotItem(0).href;
  }
});