Greasy Fork is available in English.

Ctrl+CでタイトルとURLをコピー

Shift+C:除去文字列設定  Shift+T:後回しタイトル設定

質問やレビューの投稿はこちらへ、スクリプトの通報はこちらへお寄せください。
// ==UserScript==
// @name        Ctrl+CでタイトルとURLをコピー
// @description Shift+C:除去文字列設定  Shift+T:後回しタイトル設定
// @match       *://*/*
// @version     0.6.7
// @run-at document-idle
// @grant       GM.setClipboard
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_deleteValue
// @namespace https://greasyfork.org/users/181558
// ==/UserScript==

(function() {
  const cleanUrlFirst = 0; // 1:ページ読み込み時にURLのゴミ除去を行う
  const ADD_OPEN_MULTIPLE_URL_GUIDE = 0; // 1:URL列挙した時末尾にopepn multiple urlアドオンの紹介をつける
  const YOUTUBE_DROP_PLAYLIST = 1; // 1:YouTubeの動画視聴URLでプレイリストの記述を切り落とす

  if (window != parent) return;

  var mllID;
  var sakujoRE = pref("ctrlcsakujoRE") || "";
  var cckaisuu = 0;
  var sakujoTitleRE = pref("ctrlcsakujoTitleRE") || "";

  if (cleanUrlFirst) window.history.pushState(null, null, modUrl());

  // Shift+T ページタイトル部分後回し
  sakujotitle(sakujoTitleRE);

  function sakujotitle(sakujoTitleRE) {
    if (sakujoTitleRE) {
      try {
        var hit = document.title.match(RegExp(sakujoTitleRE, "g"));
        if (hit) document.title = document.title.replace(RegExp(sakujoTitleRE, "g"), "") + " " + hit;
      } catch (e) { alert("Shift+T:\n文法エラーのようです\n\n設定値:\n" + sakujoTitleRE); }
    }
  }
  // 検索ワードをページタイトルの最初に付ける
  addtitle(/^https?:\/\/calil.jp\/local\/search/, "", '//form[@class="search"]/div/input|//input[@id="query"]'); // calil検索
  addtitle(/^https?:\/\/tv\.yahoo\.co\.jp\/search\/\?q=/, "", '//input[@class="generic_inputText floatl"]'); // yahooテレビ検索
  addtitle(/^https?:\/\/www\.nicovideo\.jp\/mylist_search\//, "", '//input[@id="search_united"]', "", "", " - マイリスト検索 "); // ニコ動マイリスト検索
  addtitle(/^https?:\/\/www\.jstage\.jst\.go\.jp\/result/, "", '//span[@class="search-parameter"]'); // J-STAGE詳細検索結果
  setTimeout(() => { addtitle(/^https?:\/\/www\.pinterest\.jp\/search\/pins\/.*q=/, "", '//input[@role="combobox"]') }, 2500); // Pinterest詳細検索結果

  if (document.title.indexOf("|") === -1) addtitle(/^https?:\/\/www\.suruga-ya\.jp\/search\?/, "", '//input[@id="searchText"]', '//div[@id="topicPath"]', /駿河屋TOP.≫.|駿河屋TOP/gi); // 駿河屋検索

  document.addEventListener("keydown", function(e) { //キー入力
      if (/input|textarea/i.test(e.target.tagName)) return;
      if (e.shiftKey && !e.altKey && !e.ctrlKey && e.which == 84) { // shift+T ページタイトル部分後回し文字列設定
        var sample = "ありません";
        if (location.href.indexOf("://www.nicovideo.jp") !== -1) sample = "キーワードで動画検索 |キーワードで|」動画|人気の「";
        if (location.href.indexOf("://www.amazon.co.jp") !== -1) sample = "Amazon.co.jp: |Amazon.co.jp: |Amazon \\|\\s|Amazon|";
        if (location.href.indexOf("auctions.yahoo.co.jp") !== -1) sample = "ヤフオク! -";
        if (location.href.indexOf("kakaku.com/") !== -1) sample = "価格.com - ";
        if (location.href.indexOf("//www.yodobashi.com/") !== -1) sample = "ヨドバシ.com - ";
        if (location.href.indexOf("//www.sukima.me/book/title/") !== -1) sample = "^\\[.*\\]";
        var str = prompt("shift+T:\r\n\"" + document.domain + "\" でページタイトルの中で後ろに移動したい文字列を正規表現で入力してください\r\n\r\nこのサイトでのお薦め設定例:\r\n" + sample + "\r\n\r\n現在値:" + (sakujoTitleRE || "なし") + "\n\n", sakujoTitleRE || "");
        sakujoTitleRE = str === null ? sakujoTitleRE : str;
        if (sakujoTitleRE != "") {
          pref("ctrlcsakujoTitleRE", sakujoTitleRE);
          sakujotitle(sakujoTitleRE);
        } else {
          pref("ctrlcsakujoTitleRE", "");
        }
        return;
      }
      if (e.shiftKey && !e.altKey && !e.ctrlKey && e.which == 67) { // shift+C 除去文字列設定
        var str = prompt("shift+C:\r\n\"" + document.domain + "\" で Ctrl+C 押下時タイトルやURLや選択文字列から除去したい文字列を正規表現で入力してください\r\n\r\n現在値:" + sakujoRE + "\r\n", sakujoRE);
        sakujoRE = str === null ? sakujoRE : str;
        if (sakujoRE != "") {
          pref("ctrlcsakujoRE", sakujoRE);
        } else {
          pref("ctrlcsakujoRE", "");
        }
        return;
      }
      if (!e.shiftKey && !e.altKey && e.ctrlKey && e.which == 67) { // ctrl+c
        if (window.getSelection() != "") {
          // 選択文字列がある
          var selection = window.getSelection().toString();
          if (sakujoRE) { // 除去文字列があれば除去してコピーも自前(なければブラウザにさせる)
            selection = tryReplace(selection, sakujoRE, "Shift+C");
            if (window.getSelection().toString() !== selection) {
              copy2cb(selection);
              e.preventDefault();
            }
          }
        } else {

          // 選択文字列がない

          var doc = location.href;
          var txt1 = doc;
          var txt2 = txt1;
          var opt = "";

          var txt2 = modUrl();
          //if (txt1 != txt2) opt += "(パラメータ除去)";

          if (/www\.youtube\.com\/embed\//.test(txt1)) txt2 = txt1.replace(/\?.*/, "").replace(/embed\//, "watch?v="); // youtube埋め込みを正規のページに

          var ret = (navigator.platform.indexOf("Win") != -1) ? "\r\n" : "\n";
          var title = document.title.replace(/ https?:.*/, "");
          title = tryReplace(title, sakujoRE, "Shift+C");

          // YouTube動画視聴画面なら
          if (location.href.match(/^https?:\/\/www\.youtube\.com\/watch\?v\=/)) { let te = eleget0('//h1[@class="title style-scope ytd-video-primary-info-renderer"]/yt-formatted-string[@force-default-style="" and @class="style-scope ytd-video-primary-info-renderer"]'); if (te) { title = te.innerText + " - YouTube"; } }

          if (cckaisuu % 1 == 0) {
            var txt = title + ret + txt2 + ret;
            var bal = "<B>" + title + "</B><BR>" + txt2;
          }
          var sort = "";

          // 列挙するタイプのサイトなら
          if (cckaisuu % 5 != 4 && /seiga\.nicovideo\.jp\/my\/manga\/favorite|webcomics\.jp\/mylist|webcomics\.jp\/$|webcomics.jp\/total$|webcomics\.jp\/bookmark|webcomics\.jp\/ranking|www.nicovideo.jp\/my\/watchlater|www\.nicovideo\.jp\/my\/mylist|seiga\.nicovideo\.jp\/my\/clip|www\.nicovideo\.jp\/my\/fav\/|www\.nicovideo\.jp\/my\/channel|www\.nicovideo\.jp\/my\/community|www\.nicovideo\.jp\/my\/top\/all|\/\/www\.netoff\.co\.jp\/cart_param|\/\/.*\.5ch\.net\/\w*\/$/.test(txt1)) {
            var rekkyo = ['//span[@class="VideoMediaObject-bodyTitle"]/../..', '//div[@class="title"]/a', '//div[@class="entry-title"]/a[1]', '//div[@class="mylistVideo"]/h5/a', '//div[@class="illust_box_li cfix"]/div/div[@class="text_ttl"]/a', '//div[@class="outer"]/div/h5/a', '//div[@class="outer"]/h5/a', '//div[@class="log-target-info"]/a', '//div[@class="mylistVideo MylistItem-videoDetail"]/h5/a|//div[@id="mainWrap"]/div[@id="main"]/ul[contains(@class,"itemList")]/li[@class="clearfix"]/dl/dd/p/a', '//div[@id="thread-list-box"]/table[@id="thread-list"]/tbody/tr/td/a'];
            txt = ""; //title+ret;
            txt2 = "";
            var num = 0;
            for (let target of rekkyo) {
              var ele = elegeta(target);
              if (cckaisuu % 5 == 1) {
                sort = " 名前↓";
                ele.sort(function(a, b) { return (a.innerText > b.innerText) ? 1 : -1; });
              }
              if (cckaisuu % 5 == 2) {
                sort = " URL↓";
                ele.sort(function(a, b) { return (a.href.split(/\/\//g)[1]) > (b.href.split(/\/\//g)[1]) ? 1 : -1; });
              }
              if (cckaisuu % 5 == 3) {
                sort = " URL↑";
                ele.sort(function(a, b) { return (a.href.split(/\/\//g)[1]) < (b.href.split(/\/\//g)[1]) ? 1 : -1; });
              }
              for (let a of ele) {
                if (a.offsetHeight) { // 非表示じゃないやつだけ
                  var cleanurl = a.href.replace(/\?track=.*|\?_topic=.*/g, "")
                  if (location.href.match(/\/\/www.nicovideo.jp\/my\/watchlater|\/\/www.nicovideo.jp\/my\/mylist\//)) { // ニコ動マイリストだけの取り込み方
                    txt += eleget0('.//span[@class="VideoMediaObject-bodyTitle"]', a).innerText.replace(/\n/gm, " ") + ret + cleanurl + ret;
                  } else { txt += a.innerText.replace(/\n/gm, " ") + ret + cleanurl + ret; }
                  txt2 += a.innerText + "<BR>" + cleanurl + "<BR>";
                  num++;
                }
              }
            }
            title += " " + num + "件" + sort;
            txt = title + ret + txt;
            if (ADD_OPEN_MULTIPLE_URL_GUIDE) txt += "\nOpen Multiple URLs - Google 検索\nhttps://www.google.co.jp/search?q=Open%20Multiple%20URLs&lr=lang_ja\n";
            var bal = "<B>" + title + "</B><BR>" + txt2;
            popup("項目の列挙<br>" + title);
          } else {
            popup("タイトルとURL<BR>" + opt);
          }

          // クリップボードにコピー
          copy2cb(txt);
          e.preventDefault();
        }
        cckaisuu++;
        return;
      }
    },
    false);
  return;

  function elegeta(xpath) {
    var ele = document.evaluate(xpath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    var array = [];
    for (var i = 0; i < ele.snapshotLength; i++) array[i] = ele.snapshotItem(i);
    return array;
  }

  function eleget0(xpath, node = document) {
    if (!xpath) return null;
    try {
      var ele = document.evaluate(xpath, node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
      return ele.snapshotLength > 0 ? ele.snapshotItem(0) : "";
    } catch (e) { return null; }
  }


  // タイトルに足す
  function addtitle(url, txt1, xpath, optionxpath = "", optionReplaceRE = /$^/, separator = " - ") {
    if (!url.test(location.href)) return;
    var ele = eleget0(xpath);
    if (!ele) return;
    ele = ele.value || ele.innerText;
    //      if (!ele) {        ele = eleget0(xpath).innerText;      }
    var ret = ele.trim() > "" ? ele.trim() + separator : "";
    if (optionxpath && eleget0(optionxpath)) {
      ret += "" + (eleget0(optionxpath).innerText.trim().replace(optionReplaceRE, "")) + " ";
    }
    document.title = ret + document.title;
    return;
  }

  // クリップボードにコピー
  function copy2cb(txt) {
    GM.setClipboard(txt);
  }

  function deleteParam(cutREs, txt1) { //余計なパラメータを除去
    var para = txt1.split(/[&?#]/);
    var txt2 = para[0] + "?";
    var j = 0;
    for (var i = 1; i < para.length; i++) {
      for (let reptxt of cutREs) {
        para[i] = para[i].replace(new RegExp("^" + reptxt + ".*"), "");
      }
      if (para[i] !== "") {
        txt2 += (j++ > 0 ? "&" : "") + para[i];
      }
    }
    return txt2.replace(/\?$/, ""); //行末が?なら削除
  }

  function modUrl() {
    var txt1 = location.href;
    var txt2 = txt1;

    if (/^https?:\/\/www\.amazon\.co\.jp\/|^https?:\/\/www\.amazon\.com\//.test(txt1) && (txt1.indexOf("/dp/product/") != -1)) // Amazonのパラメータ除去
      txt2 = "https://" + document.domain + "/dp/" + txt1.substr(txt1.indexOf("/dp/product/") + 12, 10);
    else if (/^https?:\/\/www\.amazon\.co\.jp\/|^https?:\/\/www\.amazon\.com\//.test(txt1) && (txt1.indexOf("/dp/") != -1)) // Amazonのパラメータ除去
      txt2 = "https://" + document.domain + "/dp/" + txt1.substr(txt1.indexOf("/dp/") + 4, 10);
    if (/^https?:\/\/www\.amazon\.co\.jp\/|^https?:\/\/www\.amazon\.com\//.test(txt1) && (txt1.indexOf("/ASIN/") != -1)) // Amazonのパラメータ除去
      txt2 = "https://www.amazon.co.jp/dp/" + txt1.substr(txt1.indexOf("/ASIN/") + 6, 10);
    if (/^https?:\/\/www\.amazon\.co\.jp\/|^https?:\/\/www\.amazon\.com\//.test(txt1) && (txt1.indexOf("/gp/product/") != -1)) // Amazonのパラメータ除去
      txt2 = "https://www.amazon.co.jp/dp/" + txt1.substr(txt1.indexOf("/gp/product/") + 12, 10);
    if (/^https?:\/\/www\.amazon\.co\.jp\/gp\/customer-reviews\//.test(txt1)) // Amazonのカスタマーレビューのパラメータ除去
      txt2 = deleteParam(["ref=", "ie=", "ASIN="], txt1).replace(/\/ref=.*/, "");
    txt1 = txt1.replace(/(^https?:\/\/www\.amazon\.co\.jp\/)(.*)(product-reviews\/)/, "$1$3");
    if (txt1.match(/^https?:\/\/www\.amazon\.co\.jp\/.*product-reviews\//)) // Amazonのカスタマーレビューのパラメータ除去
      txt2 = deleteParam(["ref=", "ie=", "ASIN="], txt1).replace(/\/ref=.*/, "");

    if (/^https?:\/\/www\.google\.co\.jp\/search\?|^https?:\/\/www\.google\.com\/search\?/.test(txt1)) // google検索結果のパラメータ除去
      //      txt2 = deleteParam(["ei=", "oq=", "gs_l=", "hl=", "source=", "sa=", "ved=", "biw=", "bih=", "dpr=", "ie=", "oe=", "client=", "aqs=", "sourceid=", "btgG=", "lr=", "gs_lcp=", "sclient=", "uact="], txt1);
      txt2 = deleteParam(["ei=", "oq=", "gs_l=", "hl=", "source=", "sa=", "ved=", "biw=", "bih=", "dpr=", "ie=", "oe=", "client=", "aqs=", "sourceid=", "btgG=", "gs_lcp=", "sclient=", "uact="], txt1);

    if (/^https?:\/\/books\.google\.co\.jp\/books\?/.test(txt1)) // Googleブックス検索のパラメータ除去
      txt2 = deleteParam(["souce=", "ots=", "sig=", "hl=", "sa=", "ved=", "f=", "lpg=", "dq=", "source=", "f=", "v=", cckaisuu % 2 == 0 ? "$^" : "q="], txt1); // q=を残すと検索ワードは残る

    if (/^https?:\/\/www\.ted\.com\/talks/.test(txt1)) // TEDのパラメータ除去
      txt2 = deleteParam(["awesm=", "utm_medium=", "share=", "utm_source=", "utm_campaign=", "utm_content=", "source=", "embed=", "t-", "frm_id=", "device_id=", "fb_action_ids=", "action_type_map=", "action_object_map=", "fb_source=", "fb_action_types", "action_ref_map=", "ref=", "refid=", "_ft_=", "guid="], txt1);

    if (/^https?:\/\/translate\.google\.com\/translate|^https?:\/\/translate\.googleusercontent\.com\/translate_c/.test(txt2)) { // google翻訳のパラメータ除去
      txt2 = (txt2.match(/^https?:\/\/translate\.google\.com\/translate|^https?:\/\/translate\.googleusercontent\.com\/translate_c/)[0] + txt2.match(/[\?&]u=[^&]*/)).replace(/&/, "?");
    }

    if (/^https?:\/\/seiga\.nicovideo\.jp\/comic|^https?:\/\/seiga\.nicovideo\.jp\/manga\/list|^https?:\/\/seiga\.nicovideo\.jp\/watch\/mg/.test(txt1)) txt2 = txt1.replace(/([\&\?]?[\&\?]track=.*)|(\?_topic.*)|(\?ct_now$)/, ""); // 静画(マンガ)のパラメータ除去

    if (/^https?:\/\/www\.nicovideo\.jp\/watch/.test(txt1)) txt2 = txt1.replace(/\?.*$/, ""); // ニコ動のパラメータ除去
    if (/^https?:\/\/www\.nicovideo\.jp\/user/.test(txt1)) txt2 = txt1.replace(/\?_topic.*/, ""); // ニコ動のパラメータ除去
    if (/^https?:\/\/www\.nicovideo\.jp\/tag\//.test(txt1)) txt2 = txt1.replace(/[\?&]ref=[^&]*/, ""); // ニコ動のパラメータ除去
    if (/^https?:\/\/www\.nicovideo\.jp\/search\//.test(txt1)) txt2 = txt1.replace(/\?f_range=0\&l_range=0\&opt_md=\&start=\&end=|[\?&]track=[^&]*/, ""); // ニコ動のパラメータ除去
    if (/^https?:\/\/www\.ebay\.com\/itm\/.*\?hash=/.test(txt1)) txt2 = txt1.replace(/\?hash=.*$/, ""); // eBayのパラメータ除去
    if (/^https?:\/\/ja.aliexpress.com\/item\/.*?.html\?spm=/.test(txt1)) txt2 = txt1.replace(/\?spm=.*$/, ""); // AliExpressのパラメータ除去
    if (/^https?:\/\/www.mercari.com\/jp\/items\/m51992587701\/\?_s=/.test(txt1)) txt2 = txt1.replace(/\/\?_s=.*$/, ""); // メルカリのパラメータ除去
    if (/^https?:\/\/www.reddit.com\/r\/.*\?sort=confidence/.test(txt1)) txt2 = txt1.replace(/\?sort=confidence/, ""); // redditのパラメータ除去
    if (YOUTUBE_DROP_PLAYLIST && /^https?:\/\/www.youtube.com\/watch\?v=.*\&list=/.test(txt1)) txt2 = txt1.replace(/\&list=.*/, ""); // youtubeの一時的キュープレイリストパラメータ除去
    if (/^https?:\/\/www.pinterest.jp\/search\/pins\/\?q=/.test(txt1)) txt2 = txt1.replace(/\&rs=typed.*$/, ""); // pinterestのパラメータ除去

    return txt2;
  }

  function tryReplace(str, re, title) {
    try {
      str = str.replace(RegExp(re, "gm"), "");
    } catch (e) { alert(title + ":\n文法エラーのようです\n\n設定値:\n" + re); }
    return str;
  }

  function pref(name, store = undefined) { // pref(name,data)で書き込み(数値でも文字列でも配列でもオブジェクトでも可)、pref(name)で読み出し
    var domain = (location.href.match(/^https?:\/{2,}(.*?)(?:\/|\?|#|$)/)[1] || location.href);
    if (store === undefined) { // 読み出し
      let data = GM_getValue(domain + " ::: " + name)
      if (data == undefined) return store; // 値がないなら終わり
      if (data.substr(0, 1) === "[") { // 配列なのでJSONで返す
        try { return JSON.parse(data || '[]'); } catch (e) {
          console.log("データベースがバグってるのでクリアします\n" + e);
          pref(name, []);
          return;
        }
      } else return data;
    }
    if (store === "" || store === [] || store === null) { // 書き込み、削除
      GM_deleteValue(domain + " ::: " + name);
      return store;
    } else if (typeof store === "string") { // 書き込み、文字列
      GM_setValue(domain + " ::: " + name, store);
      return store;
    } else { // 書き込み、配列
      try { GM_setValue(domain + " ::: " + name, JSON.stringify(store)); } catch (e) {
        console.log("データベースがバグってるのでクリアします\n" + e);
        pref(name, "");
      }
      return store;
    }
  }

  function popup(text) {
    var e = document.getElementById("cccbox");
    if (e) { e.remove(); }
    if (mllID) { clearTimeout(mllID); }
    var ele = document.body.appendChild(document.createElement("span"));
    ele.innerHTML = '<span id="cccbox" style="all:initial; position: fixed; right:0em; top:0em; z-index:2147483647; opacity:1; font-size:90%; font-weight:bold; margin:0px 1px; text-decoration:none !important; text-align:center; padding:1px 6px 1px 6px; border-radius:12px; background-color:#6080ff; color:white; white-space: nowrap;"">' + text + '</span>';
    mllID = setTimeout(function() { var ele = document.getElementById("cccbox"); if (ele) ele.remove(); }, 5000);
  }

})();