QR from selection / highlight

Create a QR code from text selected / highlighted.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

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

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

// @ts-check
// ==UserScript==
// @name         QR from selection / highlight
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Create a QR code from text selected / highlighted.
// @match        http://*/*
// @match        https://*/*
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.js
// ==/UserScript==

(function () {
  'use strict';

  const getSelectedText = () => {
    const activeEl = document.activeElement;
    const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;

    return activeElTagName === 'textarea' || activeElTagName === 'input'
      ? activeEl?.value.substring(
          activeEl.selectionStart,
          activeEl.selectionEnd,
        )
      : window?.getSelection()?.toString();
  };

  const createAndAppendQR = (text) => {
    let qrElement = document.getElementById('generated-qr-code');
    if (!qrElement) {
      qrElement = document.createElement('div');
      qrElement.id = 'generated-qr-code';
      document.body.appendChild(qrElement);
    }

    const qr = qrcode(0, 'L');
    qr.addData(text);
    qr.make();

    qrElement.innerHTML = qr.createImgTag(5);
    Object.assign(qrElement.style, {
      position: 'fixed',
      bottom: '0',
      right: '0',
      zIndex: '999999999',
    });
  };

  const handleEvent = () => {
    const selectedText = getSelectedText();
    if (selectedText) createAndAppendQR(selectedText);
  };

  ['mouseup', 'keyup'].forEach((eventType) => {
    document.addEventListener(eventType, handleEvent);
  });
})();