### Video.js Hook Execution Example Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/video Demonstrates the execution flow of 'beforesetup' and 'setup' hooks in Video.js. It shows how hooks are iterated and executed, and how options are merged. This code is relevant for understanding the original hook mechanism. ```javascript hooks("beforesetup").forEach(function (hookFunction) { var opts = hookFunction(el, mergeOptions$3(options)); if (!isObject$1(opts) || Array.isArray(opts)) { log$1.error("please return an object in beforesetup hooks"); return; } options = mergeOptions$3(options, opts); }); // We get the current "Player" component here in case an integration has // replaced it with a custom player. var PlayerComponent = Component$1.getComponent("Player"); player = new PlayerComponent(el, options, ready); hooks("setup").forEach(function (hookFunction) { return hookFunction(player); }); ``` -------------------------------- ### Verify Node.js Installation Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/Nodejs%E7%AE%80%E4%BB%8B%E4%B8%8E%E5%AE%89%E8%A3%85 This command verifies that Node.js has been successfully installed on your system. After installation, open a new command prompt or terminal and execute this command to display the installed Node.js version. ```bash node -v ``` -------------------------------- ### Install npm Packages Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/npm%E7%AE%80%E4%BB%8B Installs npm packages. `--save` adds packages to `dependencies` (needed for production), while `--save-dev` adds them to `devDependencies` (needed for development). `i` is a shorthand for `install`. ```bash npm i --save npm install --save-dev npm i --save ``` -------------------------------- ### Vue 3 Component Setup and Data Access Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/Vue3%E7%9A%84%E5%88%9D%E6%AD%A5%E5%A4%84%E7%90%86%E6%96%B9%E6%A1%88 Demonstrates the basic structure of a Vue 3 component using the `setup` function and how to access reactive data. It shows how `ref` creates reactive references and how these are stored within the component instance. ```javascript const { createApp, ref } = Vue; createApp({ setup() { debugger; const message = ref("Hello vue!"); return { message, }; }, created() { console.log("created"); }, }).mount("#app"); ``` ```javascript const { setup } = Component; if (setup) { pauseTracking(); const setupContext = (instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null); const reset = setCurrentInstance(instance); const setupResult = callWithErrorHandling(setup, instance, 0, [ shallowReadonly(instance.props), setupContext, ]); } ``` ```javascript function handleSetupResult(instance, setupResult, isSSR) { if (isFunction(setupResult)) { { instance.render = setupResult; } } else if (isObject(setupResult)) { instance.setupState = proxyRefs(setupResult); } } ``` ```javascript class RefImpl { constructor(value, isShallow2) { this.dep = new Dep(); this["__v_isRef"] = true; this["__v_isShallow"] = false; this._rawValue = isShallow2 ? value : toRaw(value); this._value = isShallow2 ? value : toReactive(value); this["__v_isShallow"] = isShallow2; } get value() { { this.dep.track({ target: this, type: "get", key: "value", }); } return this._value; } set value(newValue) { const oldValue = this._rawValue; const useDirectValue = this["__v_isShallow"] || isShallow(newValue) || isReadonly(newValue); newValue = useDirectValue ? newValue : toRaw(newValue); if (hasChanged(newValue, oldValue)) { this._rawValue = newValue; this._value = useDirectValue ? newValue : toReactive(newValue); { this.dep.trigger({ target: this, type: "set", key: "value", newValue, oldValue, }); } } } } ``` -------------------------------- ### Custom video.js Hook Implementation Example Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/video 提供了一个使用 `videojs.hook` 的实际示例,展示了如何在 `beforesetup` 阶段修改播放器选项,以及在 `setup` 阶段控制已创建的播放器实例。这是通过 video.js 的扩展点进行劫持或定制的有效方式。 ```javascript videojs.hook("beforesetup", function (videoEl, options) { //修改选项 return options; }); videojs.hook("setup", function (player) { //控制实例 }); ``` -------------------------------- ### Video.js 钩子函数示例 Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%AE%9E%E6%88%98%E7%AF%87/%E5%AE%9E%E6%88%9891%E5%AD%A6%E4%B9%A0%E7%BD%91videojs%E5%8E%BB%E5%B9%BF%E5%91%8A 展示了 videojs 提供的 `beforesetup` 和 `setup` 钩子函数的使用方法。`beforesetup` 在初始化前调用,允许修改配置;`setup` 在初始化后调用,允许操作 player 对象。 ```javascript // 初始化之前会调用beforesetup钩子,传入el元素和config配置对象 videojs.hook("beforesetup", function (videoEl, options) { // videoEl will be the video element with id="some-id" since that // gets passed to videojs() below. On subsequent calls, it will be // different. videoEl.className += " some-super-class"; // autoplay will be true here, since we passed it as such. if (options.autoplay) { options.autoplay = false; } // Options that are returned here will be merged with old options. // // In this example options will now be: // {autoplay: false, controls: true} // // This has the practical effect of always disabling autoplay no matter // what options are passed to videojs(). return options; }); // 初始化之后会调用setup钩子,传入初始化好的player对象 videojs.hook("setup", function (player) { // Initialize the foo plugin after any player is created. player.foo(); }); ``` -------------------------------- ### Example package.json Structure Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/npm%E7%AE%80%E4%BB%8B Illustrates the typical structure and key fields within a `package.json` file, including name, version, description, main entry point, scripts, author, and license. ```json { "name": "pack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } ``` -------------------------------- ### Check npm Version Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/npm%E7%AE%80%E4%BB%8B Displays the currently installed version of npm. This is a fundamental check to ensure npm is accessible and to identify the version being used. ```bash npm -v ``` -------------------------------- ### Basic Express HTTP Server Setup in Node.js Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E7%95%AA%E5%A4%96%E7%AF%87/%E5%AE%9E%E7%8E%B0Node This snippet demonstrates the basic setup of an HTTP server using the Express framework in Node.js. It initializes an Express application, enables JSON request body parsing, and defines two POST endpoints: '/submit' and '/search'. The server listens on port 3000. ```javascript const express = require("express"); const app = express(); app.use(express.json()); app.post("/submit", (req, res) => { res.send("POST request to the homepage"); }); app.post("/search", (req, res) => { res.send("POST request to the homepage"); }); app.listen(3000, () => { console.log(`fuzzySearch app listening on port !`); }); ``` -------------------------------- ### video.js Hook Mechanism for Setup Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/video 演示了 video.js 的 `hook` 机制,允许在播放器设置的 `beforesetup` 和 `setup` 阶段注入自定义逻辑。`beforesetup` 钩子可以在播放器初始化前修改选项,而 `setup` 钩子可以在播放器创建后进行操作。 ```javascript videojs.hook("beforesetup", function (videoEl, options) { // videoEl will be the video element with id="some-id" since that // gets passed to videojs() below. On subsequent calls, it will be // different. videoEl.className += " some-super-class"; // autoplay will be true here, since we passed it as such. if (options.autoplay) { options.autoplay = false; } // Options that are returned here will be merged with old options. return options; }); videojs.hook("setup", function (player) { // Initialize the foo plugin after any player is created. player.foo(); }); ``` -------------------------------- ### 移除 Video.js 广告的实现 Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%AE%9E%E6%88%98%E7%AF%87/%E5%AE%9E%E6%88%9891%E5%AD%A6%E4%B9%A0%E7%BD%91videojs%E5%8E%BB%E5%B9%BF%E5%91%8A 通过劫持 videojs 的 `setup` 钩子,在 player 初始化后,重写 `player.on` 方法。当监听 `playing` 事件时,替换原有的回调函数为一个简单的 `player.play()` 调用,从而阻止广告的触发。 ```javascript unsafeWindow._videojs = undefined; Object.defineProperty(unsafeWindow, "videojs", { get() { let result = unsafeWindow._videojs; return result; }, set(obj) { obj.hook("setup", function (player) { window.player = player; let originOn = player.on; player.on = function (...args) { if (args.length >= 1 && args[0] === "playing") { args[1] = function () { player.play(); }; } return originOn.call(this, ...args); }; }); unsafeWindow._videojs = obj; }, }); ``` -------------------------------- ### Initializing and Using MutationObserver Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/MutationObserve%20%E7%9F%A5%E8%AF%86/MutationObserve%E7%9A%84%E7%94%B1%E6%9D%A5 This example shows how to initialize a MutationObserver to monitor a specific DOM node. It includes configuration options for observing attribute changes, child list modifications, and subtree changes, along with a callback function to handle detected mutations and an example of disconnecting the observer. ```javascript const targetNode = document.getElementById("some-id"); // 观察器的配置(需要观察什么变动) const config = { attributes: true, childList: true, subtree: true }; //subtree 监听包括target的整个子树 //childList 监听子节点的新增与删除变化 //attributes 监听节点的属性变化 // 当观察到变动时执行的回调函数 const callback = function (mutationsList, observer) { for (let mutation of mutationsList) { if (mutation.type === "childList") { console.log("节点被增加或删除"); } else if (mutation.type === "attributes") { console.log("名为:" + mutation.attributeName + "的属性被修改"); } } }; // 创建一个观察器实例并传入回调函数 // observe函数会对传入的节点以及所需观察的配置项进行观察 // 发生改变则回调callback函数 const observer = new MutationObserver(callback); // 以上述配置开始观察目标节点 observer.observe(targetNode, config); // 可停止观察 observer.disconnect(); ``` -------------------------------- ### toastr Demo - UserScript Setup and Info Message Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/toastr%E5%AE%9E%E7%8E%B0%E6%B6%88%E6%81%AF%E6%8F%90%E7%A4%BA This snippet demonstrates how to set up a UserScript for toastr, including requiring the toastr library and CSS, and then displays an informational message using toastr.info(). It requires the toastr library and its associated CSS. ```javascript // ==UserScript== // @name toastr Demo // @namespace https://bbs.tampermonkey.net.cn/ // @version 0.1.0 // @description try to take over the world! // @author You // @require https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.js // @resource CSS https://cdn.bootcdn.net/ajax/libs/toastr.js/2.1.4/toastr.min.css // @match https://bbs.tampermonkey.net.cn/* // @grant GM_getResourceText // @grant GM_addStyle // @grant unsafeWindow // ==/UserScript== GM_addStyle(GM_getResourceText("CSS")); toastr.info("Are you the 6 fingered man?"); ``` -------------------------------- ### Initialize Ace Editor and Check for Equality Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E7%95%AA%E5%A4%96%E7%AF%87/Script%E6%A0%87%E7%AD%BE%E5%88%9D%E5%A7%8B%E5%8C%96%E5%AF%B9%E8%B1%A1%E5%8A%AB%E6%8C%81 Demonstrates the initialization of an Ace editor using `ace.edit()` and verifies that repeated initializations return the same editor instance. This is a basic example showing how Ace editors can be managed. ```javascript // ace初始化编辑器通常使用ace.edit函数进行初始化 console.log(ace.edit("code_editor") === ace.edit("code_editor")); //true ``` -------------------------------- ### Basic SweetAlert2 Dialog Example Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/SweetAlert2%E5%AE%9E%E7%8E%B0%E5%AF%B9%E8%AF%9D%E6%A1%86 Demonstrates the fundamental usage of SweetAlert2 to display a simple dialog box with a message. This is the most basic way to invoke the library's core functionality. ```javascript Swal.fire("Any fool can use a computer"); ``` -------------------------------- ### Initialize JSZip Objects Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/JSZip%E5%8E%8B%E7%BC%A9%E8%A7%A3%E5%8E%8B%E6%96%87%E4%BB%B6 Initializes two JSZip objects: 'inZip' for reading the input zip file and 'outZip' for creating the output zip file. This is a standard setup for processing zip archives. ```javascript var inZip = new JSZip(); var outZip = new JSZip(); ``` -------------------------------- ### Defining a Simple AMD Module Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9F%A5%E8%AF%86/AMD%E6%A8%A1%E5%9D%97%E5%8C%96%E4%BB%8B%E7%BB%8D Illustrates how to define an AMD module using the `define` function. This example defines a module that exports a `printHello` function. When `require` is used without `require.config`, it looks for a corresponding JS file with the module name. ```javascript //假设是hello.js则模块名是hello define(function (require) { const printHello = () => { console.log("hello"); }; return { printHello, }; }); ``` -------------------------------- ### Define Property with Accessor Descriptor (Get/Set) in JavaScript Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%B1%9E%E6%80%A7%E5%8A%AB%E6%8C%81 This example shows how to define a property using `Object.defineProperty` with accessor descriptors (`get` and `set`). These functions allow custom logic to be executed when the property is accessed or modified. ```javascript Object.defineProperty(obj, "attr", { get: function () { // Custom getter logic }, set: function (str) { // Custom setter logic }, }); ``` -------------------------------- ### Making Ajax Requests with jQuery Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/Jquery%E5%BC%95%E7%94%A8 jQuery provides a simplified and unified way to make Ajax requests across different browsers, abstracting away the complexities of native JavaScript's XMLHttpRequest object. This example demonstrates a basic Ajax GET request and how to handle its completion. ```javascript $.ajax({ url: "test.html", context: document.body, }).done(function () { $(this).addClass("done"); }); ``` -------------------------------- ### Vue 3 Use Function - Plugin Installation Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/Vue3%E7%9A%84%E5%88%9D%E6%AD%A5%E5%A4%84%E7%90%86%E6%96%B9%E6%A1%88 This snippet shows the implementation of the `use` function in Vue 3, which is responsible for installing plugins. It checks if a plugin has already been installed and handles both function-based plugins and plugins with an `install` method. ```javascript use(plugin, ...options) { if (installedPlugins.has(plugin)) { warn$1(`Plugin has already been applied to target app.`); } else if (plugin && isFunction(plugin.install)) { installedPlugins.add(plugin); plugin.install(app, ...options); } else if (isFunction(plugin)) { installedPlugins.add(plugin); plugin(app, ...options); } else { warn$1( `A plugin must either be a function or an object with an "install" function.` ); } return app; } ``` -------------------------------- ### Initialize npm Project Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/npm%E7%AE%80%E4%BB%8B Initializes a new Node.js project in the current directory by creating a `package.json` file. This file stores metadata and dependency information for the project. The `-y` flag accepts defaults. ```bash npm init npm init -y ``` -------------------------------- ### 初始化 NPM 项目 Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/NPM%E5%8F%91%E5%B8%83%E9%AD%94%E6%94%B9%E5%8C%85 创建一个新的目录并使用 npm init 命令初始化一个新的 NPM 项目。此命令会引导用户输入项目相关信息,生成 package.json 文件。 ```bash mkdir example-project cd example-project npm init ``` -------------------------------- ### Vue 3 WeakSet for Installed Plugins Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E4%B8%AD%E7%BA%A7%E7%AF%87/Vue3%E7%9A%84%E5%88%9D%E6%AD%A5%E5%A4%84%E7%90%86%E6%96%B9%E6%A1%88 This code snippet reveals that Vue 3 uses a `WeakSet` named `installedPlugins` to keep track of already installed plugins. This is a common pattern for ensuring that plugins are only installed once. ```javascript const installedPlugins = /* @__PURE__ */ new WeakSet(); ``` -------------------------------- ### Initialize SQLite Database and Load Extension Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E7%95%AA%E5%A4%96%E7%AF%87/%E5%AE%9E%E7%8E%B0Node Initializes the SQLite database by loading a custom extension and setting up a virtual table for fuzzy searching. It requires the 'path' module for resolving file paths and assumes the existence of 'simple' extension and a 'dict' directory. ```javascript function startSqlite() { db.serialize(function () { db.loadExtension(path.resolve("./", "simple")); db.run("select jieba_dict(?)", path.resolve("./", "dict")); db.run( "CREATE VIRTUAL TABLE if not exists fuzzySearch USING fts5(question,answer,type UNINDEXED, tokenize = 'simple у')" ); }); } ``` -------------------------------- ### Observe Attribute Modifications with MutationObserver Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/MutationObserve%20%E7%9F%A5%E8%AF%86/MutationObserve%E4%BE%8B%E5%AD%90 This example shows how to use MutationObserver to monitor changes to an element's attributes. It observes attribute additions, removals, and updates. The observer is configured with `attributes: true` and `attributeOldValue: true` to capture attribute name and its previous value. ```javascript const target = document.querySelector(".target"); let observer = new MutationObserver(function (mutations) { console.log("mutations", mutations); }); observer.observe(target, { attributes: true, attributeOldValue: true, }); target.setAttribute("env", "test"); target.removeAttribute("env"); ``` -------------------------------- ### Create JSZip Instance Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/JSZip%E5%8E%8B%E7%BC%A9%E8%A7%A3%E5%8E%8B%E6%96%87%E4%BB%B6 Initializes a new JSZip instance, which represents a collection of files and folders that can be manipulated. ```javascript var zip = new JSZip(); ``` -------------------------------- ### Add Files and Folders with JSZip Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/JSZip%E5%8E%8B%E7%BC%A9%E8%A7%A3%E5%8E%8B%E6%96%87%E4%BB%B6 Demonstrates how to add files and create nested directories within a JSZip instance. The `file` and `folder` methods return the zip instance, enabling chained calls. ```javascript // Create a file zip.file("hello.txt", "Hello[p my)6cxsw2q"); // Supports newline characterszip.file("hello.txt", "Hello World\n"); // Create a file in a nested directoryzip.file("nested/hello.txt", "Hello World\n"); // Create a directory and then a file within itzip.folder("nested").file("hello.txt", "Hello World\n"); var photoZip = zip.folder("photos"); // Equivalent to creating photos/README photoZip.file("README", "a folder with photos"); ``` -------------------------------- ### Observe Character Data Changes with MutationObserver Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/MutationObserve%20%E7%9F%A5%E8%AF%86/MutationObserve%E4%BE%8B%E5%AD%90 This example shows how to monitor changes in the character data (text content) of a target element and its descendants. It utilizes the `characterData` and `subtree` options, along with `characterDataOldValue` to capture the previous text content. The observer logs mutation records for each text modification. ```javascript const target = document.querySelector(".target"); let observer = new MutationObserver(function (mutations) { console.log("mutations", mutations); }); observer.observe(target, { characterData: true, characterDataOldValue: true, subtree: true, }); target.childNodes[0].textContent = "text1"; target.childNodes[0].textContent = "text2"; ``` -------------------------------- ### Observe Child List Modifications with MutationObserver Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/MutationObserve%20%E7%9F%A5%E8%AF%86/MutationObserve%E4%BE%8B%E5%AD%90 This example demonstrates how to use MutationObserver to detect changes in the child elements of a target DOM node. It observes additions and removals of child nodes and logs detailed MutationRecord objects for each change. The observer is configured with `childList: true` to track these modifications. ```javascript const target = document.querySelector(".target"); let observer = new MutationObserver(function (mutations) { console.log("mutations", mutations); }); observer.observe(target, { childList: true, }); const childList1 = document.createElement("div"); childList1.innerText = "div1"; target.append(childList1); const childList2 = document.createElement("div"); childList2.innerText = "div2"; target.append(childList2); childList2.remove(); childList1.remove(); ``` -------------------------------- ### Tampermonkey Save Script Payload Example (JSON) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E9%AB%98%E7%BA%A7%E7%AF%87/%E6%8A%B9%E5%B9%B3Tampermonkey%E7%9A%84VSCode%E5%BC%80%E5%8F%91%E4%BD%93%E9%AA%8C This is an example of the data payload captured when saving a script in Tampermonkey. It includes properties like `auto_save`, `clean`, `code`, `method`, `new_script`, `reload`, and `uuid`, providing insight into the data structure used for script persistence. ```json { "auto_save": undefined; "clean": false; "code": "脚本代码"; "force": undefined; "lastModTime": undefined; "method": "saveScript"; "new_script": true; "reload": true; "restore": undefined; "uuid": "new-user-script"; } ``` -------------------------------- ### 完整HelloWorld油猴脚本示例 (JavaScript) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%85%A5%E9%97%A8%E7%AF%87/%E7%AC%AC%E4%B8%80%E4%B8%AA%E8%84%9A%E6%9C%AC-HelloWorld 这是一个完整的油猴脚本示例,它包含修改后的元数据和JavaScript代码,用于在指定的论坛首页弹出'HelloWorld'对话框。脚本的元数据(如@name, @description, @author)已被更新。 ```javascript // ==UserScript== // @name 第一个脚本-HelloWorld // @namespace https://learn.scriptcat.org/ // @version 0.1 // @description 第一个脚本!弹出HelloWorld对话框 // @author 李恒道 & 涛之雨 // @match https://bbs.tampermonkey.net.cn/ // @grant none // ==/UserScript== (function() { 'use strict'; alert('HelloWorld'); // Your code here... })(); ``` -------------------------------- ### Hijacking the Date Object (Example) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%85%A5%E9%97%A8%E7%AF%87/hook%E5%AE%9E%E7%8E%B0b%E7%AB%99%E8%AF%84%E8%AE%BA%E5%B0%8F%E5%B0%BE%E5%B7%B4 This snippet demonstrates hijacking the global `Date` object. It replaces the `Date` constructor and its prototype methods to potentially alter how dates are created and displayed. The example shows how to return a modified date or the original input, and how to access original date methods. ```javascript ;(()=>{ const Date_=Date; Date=function(a){ const d=new Date_(a); this.tao=a; this.zhiyu=d; return isNaN(d)?a:d; }; Object.getOwnPropertyNames(Date_.prototype).map(a=>{ Date.prototype[a]=function(){ const d=new Date_(this.zhiyu)[a](); return isNaN(d)?this.tao:d; }; }); Date.now=Date_.now; })(); ``` -------------------------------- ### 粘合服务器与客户端代码 Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E9%AB%98%E7%BA%A7%E7%AF%87/%E6%8A%B9%E5%B9%B3Tampermonkey%E7%9A%84VSCode%E5%BC%80%E5%8F%91%E4%BD%93%E9%AA%8C 主入口文件,用于协调本地服务器的启动和客户端的初始化。它首先调用 `server.initLocalServer()` 获取可用的端口,然后将端口传递给 `client.init()` 来启动客户端逻辑。 ```javascript const server = require("./server/index.js"); const client = require("./client/index.js"); async function init() { const port = await server.initLocalServer(); client.init({ port }); console.log("port", port); } init(); exports.init = init; ``` -------------------------------- ### 添加JavaScript弹窗到油猴脚本 (JavaScript) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%85%A5%E9%97%A8%E7%AF%87/%E7%AC%AC%E4%B8%80%E4%B8%AA%E8%84%9A%E6%9C%AC-HelloWorld 此代码片段在油猴脚本中添加了一个简单的JavaScript弹窗,用于在访问匹配的URL时显示'HelloWorld'消息。这是实现脚本基本功能的示例。 ```javascript // ==UserScript== // @name New Userscript // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author You // @match https://bbs.tampermonkey.net.cn/ // @grant none // ==/UserScript== (function() { 'use strict'; alert('HelloWorld') // Your code here... })(); ``` -------------------------------- ### Modifying Array Reduce Behavior (Example) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%85%A5%E9%97%A8%E7%AF%87/hook%E5%AE%9E%E7%8E%B0b%E7%AB%99%E8%AF%84%E8%AE%BA%E5%B0%8F%E5%B0%BE%E5%B7%B4 This code snippet modifies the `reduce` method of arrays. It checks if the string representation of the array includes 'github-sync'. If it does, it maps over the array, changing `false` values to `true` before applying the original `reduce` function. This is an example of modifying built-in array methods for specific use cases. ```javascript [].constructor.prototype._reduce=[].constructor.prototype._reduce||[].constructor.prototype.reduce; [].constructor.prototype.reduce=function(){ return(JSON.stringify(this).includes('github-sync')?this.map(a=>{ for(const i in a)a[i]===false&&(a[i]=true); return a; }):this)._reduce(arguments[0],arguments[1]); }; ``` -------------------------------- ### Configure npm Registry to Taobao Mirror Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%B7%A5%E7%A8%8B%E7%AF%87/npm%E7%AE%80%E4%BB%8B Changes the npm download registry to the Taobao mirror for faster package downloads in certain regions. It also shows how to verify the change and reset to the official registry. ```bash npm config set registry https://registry.npm.taobao.org npm config get registry npm config set registry https://registry.npmjs.org/ ``` -------------------------------- ### 登录 NPM 账号 Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/NPM%E5%8F%91%E5%B8%83%E9%AD%94%E6%94%B9%E5%8C%85 使用 npm login 命令登录到 NPM 账户。如果遇到 500 错误,需要更换 NPM 镜像源。登录时需要输入用户名、密码和邮箱。 ```bash npm login Username:xxxxx Password: //密码不会显示星号 Email:(this IS public) example@xx.com //自己的邮箱 Logged in as username on https://registry.npmjs.org/ ``` ```bash npm config set registry https://registry.npmjs.org/ ``` -------------------------------- ### Using DynamicLoad Class (JavaScript) Source: https://learn.scriptcat.org/%E6%B2%B9%E7%8C%B4%E6%95%99%E7%A8%8B/%E5%AE%9E%E6%88%98%E7%AF%87/%E7%9B%91%E5%90%ACB%E7%AB%99%E5%8A%A8%E6%80%81%E7%9A%84%E5%8A%A0%E8%BD%BD%E7%9A%84%E6%A8%A1%E5%9D%97 Illustrates the usage of the `DynamicLoad` class in JavaScript. It covers creating an instance, fetching existing items, and setting up an event listener for 'dynamicUpdate' to handle new content. ```javascript // 声明DynamicLoad类, 并绑定上页面监听器 const dynamic = new DynamicLoad(); // 获取目前已加载的所有动态 const loadedDynamicList = dynamic.items; console.log(loadedDynamicList); // 监听动态加载 window.addEventListener("dynamicUpdate", (e) => { // 获取新加载的动态 const appendDynamicList = e.detail; console.log(appendDynamicList); }); ``` -------------------------------- ### Load Zip File with JSZip Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/%E5%BC%95%E7%94%A8%E5%BA%93%E4%BD%BF%E7%94%A8/JSZip%E5%8E%8B%E7%BC%A9%E8%A7%A3%E5%8E%8B%E6%96%87%E4%BB%B6 Demonstrates how to load an existing zip file's content into a new JSZip instance using the `loadAsync` method. The content must be provided in a binary format. ```javascript var new_zip = new JSZip(); // more files ! new_zip.loadAsync(content).then(function (zip) { // you now have every files contained in the loaded zip zip.file("hello.txt").async("string"); // a promise of "Hello World\n" }); ``` -------------------------------- ### Callback Hell Example (JavaScript) Source: https://learn.scriptcat.org/%E5%AE%9E%E7%94%A8%E7%9F%A5%E8%AF%86%E5%BA%93/JavaScript%20%E7%9F%A5%E8%AF%86%E7%AF%87/Promise%20%E7%9F%A5%E8%AF%86/%E4%B8%BA%E4%BB%80%E4%B9%88%E9%9C%80%E8%A6%81Promise Demonstrates the 'callback hell' or 'pyramid of doom' problem in JavaScript, where nested callbacks lead to deeply indented and hard-to-read code. ```javascript function sleep(callback) { setTimeout(() => { callback(); }, 3000); } console.log("“执行了"); sleep(() => { console.log("我等待了3s"); sleep(() => { console.log("我等待了6s"); sleep(() => { console.log("我等待了9s"); sleep(() => { console.log("我等待了12s"); }); }); }); }); ```