Greasy Fork

Greasy Fork is available in English.

划词二维码

选中文字或链接,按键盘 Q 一键显示二维码!

当前为 2020-08-08 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         划词二维码
// @namespace    https://mings.work/
// @version      0.3
// @description  选中文字或链接,按键盘 Q 一键显示二维码!
// @author       Ming
// @match        http://*/*
// @match        https://*/*
// @run-at       document-end
// @grant        none
// @require      https://cdn.jsdelivr.net/npm/[email protected]/build/qrcode.min.js
// ==/UserScript==

(function () {
  "use strict";
  let selection;
  let position;
  document.onselectionchange = function () {
    selection = document.getSelection();


    if (!selection || selection && selection.toString().length < 1) {
      tryClearCanvas()
    }
  };


  function insertButton() {
    var qrCanvas = document.createElement("canvas");
    qrCanvas.id = Date.now();
    qrCanvas.className = "qr-canvas"
    qrCanvas.style = `position: fixed; left: ${position.x ? position.x : "0"}px; top: ${position.y ? position.y - window.screen.availTop : "0"}px; z-index: 99999;`

    var range = selection.getRangeAt(0);
    const newRange = document.createRange();

    newRange.setStart(selection.focusNode, range.endOffset);
    newRange.insertNode(qrCanvas);


    var qrcodeText = selection.toString()
    if (selection.baseNode.parentElement.href) qrcodeText = selection.baseNode.parentElement.href

    QRCode.toCanvas(
      qrCanvas,
      qrcodeText,
      function (error) {
        if (error) console.error(error);
        console.log("success!");
      }
    );
  }

  function tryClearCanvas() {
    if (document.getElementsByClassName("qr-canvas")) {
      const qrCanvasList = document.getElementsByClassName("qr-canvas")

      for (let element of qrCanvasList) {
        element.remove();
      }
    }
  }

  document.addEventListener(
    "keydown",
    (e) => {
      if (e.key === "q") {
        if (selection && (selection.toString().length > 0 || selection.baseNode.parentElement.href)) {
          insertButton()
        }
      }
    },
    false
  );

  document.addEventListener('mouseup', e => {
    position = {
      x: e.clientX,
      y: e.clientY
    };
  });
})();