跳转至

前端代码片段

个人常用的前端小片段:黑暗模式书签、fetch 提交、油猴脚本。

🌙 黑暗模式

F12 控制台直接给页面套滤镜:

控制台
document.documentElement.style.filter = 'invert(85%) hue-rotate(180deg)'

或把下面这段存成浏览器书签,点击循环切换三档(原色 / 85% / 100%):

书签 JS
javascript: (function () {  const docStyle = document.documentElement.style;  if (!window.modeIndex) {    window.modeIndex = 0;  }  const styleList = [    '',    'invert(85%) hue-rotate(180deg)',   'invert(100%) hue-rotate(180deg)',  ];  modeIndex = modeIndex >= styleList.length - 1 ? 0 : modeIndex + 1;  docStyle.filter = styleList[modeIndex];  document.body.querySelectorAll('img, picture, video').forEach(el => el.style.filter = modeIndex ? 'invert(1) hue-rotate(180deg)' : '');})();

书签用法

新建书签时把名称设为「黑暗模式」、网址粘贴上面这行 javascript: 代码即可;再次点击会在三档之间循环。

📮 js 发送 HTTP POST 请求

fetch · X-CSRFToken · JSON.stringify。Django 模板里提交 JSON 的写法。

function send_seed(value1) {
    var data = {
        webhook: value1,
    };
    // 配置 fetch 请求
    fetch("/addfeed", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            'X-CSRFToken': '{{csrf_token}}'  // (1)!
        },
        body: JSON.stringify(data)
    })
        .then(function (response) {
            if (response.ok) {
                // 解析响应数据
                return response.json();
            } else {
                // 请求失败
                throw new Error("请求失败");
            }
        })
        .then(function (responseData) {
            // 请求成功,处理响应数据
            console.log(responseData);
        })
        .catch(function (error) {
            // 处理错误
            console.error(error);
        });
}
  1. Django 模板变量,CSRF 校验必需;配合后端 CSRF_TRUSTED_ORIGINS 使用。

🐒 油猴脚本

referrerpolicy · getElementsByTagName · setAttribute。给图片补属性绕过防盗链。

给图片添加属性 referrerpolicy="no-referrer"

tampermonkey.js
(function () {
    'use strict';

    // 获取所有的 img 标签
    var images = document.getElementsByTagName('img');

    // 遍历所有 img 标签并添加 referrerpolicy 属性
    for (var i = 0; i < images.length; i++) {
        images[i].setAttribute('referrerpolicy', 'no-referrer');
    }
})();