通过 HTML 按钮动态添加新的 UserScript

Dynamically add new UserScript via an HTML button

我正在为 post 我制作的一些脚本创建一个网站,我想在我的页面上创建一个按钮来使用 Tampermonkey 或 Greasemonkey 动态安装 UserScript,就像在 Greasyfork.

页面示例:Script example

您可以尝试使用隐藏的 <a> 元素触发下载,该元素的 download 属性设置为以 .user.js 结尾的文件名。您可能需要在浏览器中 enable some settings 来检测用户脚本的下载打开。

注意:您可能需要将文本发送到服务器(PHP、Node等...),将文件保存为*.user.js 然后创建一个 <iframe>,其中 href 指向服务器上的文件名以触发正确的文件 download/install。当您在 Greasyfork 上安装脚本时,它会下载托管在其服务器上的 *.user.js 文件。下载的文件名符合以下模式:

https://greasyfork.org/scripts/<ID>-script-name/code/Script%20Name.user.js

现代 Web 开发人员不赞成从客户端或本地文件系统下载脚本。

const download = (content, mimeType, filename) => {
  const
    a = document.createElement('a'),
    blob = new Blob([content], {type: mimeType}),
    url = URL.createObjectURL(blob);
  a.setAttribute('href', url);
  a.setAttribute('download', filename);
  a.click();
  console.log(`Downloading: ${filename}`);
};

const extractFilenameFromScript = (script) => {
  const [, scriptName] = script.match(/^\/\/\s*@name\s+(.+)$/m);
  return `${scriptName.replace(/[^a-z0-9]+/ig, '-').toLowerCase()}.user.js`;
};

const downloadScript = () => {
  const script = document.querySelector('.user-script').textContent.trim();
  const filename = extractFilenameFromScript(script);
  download(script, 'text/javascript', filename);
};

document.querySelector('.download-btn').addEventListener('click', downloadScript);
.user-script {
  width: 100%;
  height: 8em;
}
<textarea class="user-script">// ==UserScript==
// @name         My Awesome Script
// @namespace    com.Whosebug.questions
// @version      1.0.0
// @description  An example UserScript to download
// @author       Mr. Polywhirl
// @match        
// @grant        none
// ==/UserScript==
(function() {
    'use strict';
    alert('Hello World');
})();
</textarea>
<button class="download-btn">Download</button>