便捷复制页签 title

Ctrl + q 复制页签标题;Alt + q 复制页签标题及链接,生成 markdown 格式

目前为 2023-03-23 提交的版本。查看 最新版本

// ==UserScript==
// @name         Copy title
// @name:zh-CN   便捷复制页签 title
// @namespace    http://tampermonkey.net/Henry
// @version      1.0.0
// @description  use Ctrl + q copy title; Alt + q copy title and url, create markdown
// @description:zh-CN   Ctrl + q 复制页签标题;Alt + q 复制页签标题及链接,生成 markdown 格式
// @author       Henry
// @icon         https://tsz.netlify.app/img/favicon.png
// @match        http*://*/*
// @license      MIT
// @resource css  https://gitee.com/mirrors/jsMessage/raw/master/codebase/themes/message_solid.css
// @grant        GM_addStyle
// @grant        GM_getResourceText
// ==/UserScript==

(function () {
  'use strict';

  addScript();

  function addScript() {
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://gitee.com/mirrors/jsMessage/raw/master/codebase/message.js';
    document.head.appendChild(script);
  }
  GM_addStyle(GM_getResourceText('css'));

  document.addEventListener('keydown', listener, false);

  function listener(event) {
    const { keyCode, ctrlKey, altKey } = event;
    if (keyCode === 81 && ctrlKey) {
      event.preventDefault();
      event.stopPropagation();
      copyTextToClipboard(document.title);
      return false;
    }
    if (keyCode === 81 && altKey) {
      event.preventDefault();
      event.stopPropagation();
      copyTextToClipboard(`[${document.title}](${location.href})`);
      return false;
    }
  }

  function copyTextToClipboard(text) {
    if (!navigator.clipboard) {
      fallbackCopyTextToClipboard(text);
      return;
    }
    navigator.clipboard.writeText(text).then(
      function () {
        wrapperMsg('Copying: ' + text);
      },
      function (err) {
        wrapperMsg('Oops, unable to copy');
      }
    );
  }

  function wrapperMsg(input) {
    window.dhtmlx.message(input);
  }

  function fallbackCopyTextToClipboard(text) {
    let textArea = document.createElement('textarea');
    textArea.value = text;

    // Avoid scrolling to bottom
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.position = 'fixed';

    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      var successful = document.execCommand('copy');
      var msg = successful ? text : '';
      wrapperMsg('Copying: ' + msg);
    } catch (err) {
      wrapperMsg('Oops, unable to copy');
    }

    document.body.removeChild(textArea);
  }
})();