You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Tampermonkey在GitHub页面加载localhost图片(绕过CSP限制)

绕过GitHub CSP限制,用Tampermonkey加载localhost图片

GitHub页面的Content Security Policy(CSP)会限制img标签加载非白名单内的资源,直接用<img src="localhost地址">或blob URL都会触发拦截。要解决这个问题,核心思路是利用Tampermonkey的特权API绕过CSP,再将图片转成符合CSP规则的格式加载。

具体实现步骤

  1. 配置脚本权限
    在Tampermonkey脚本头部添加必要的权限声明:

    • // @grant GM_xmlhttpRequest:启用Tampermonkey的特权请求API,不受页面CSP约束
    • // @connect localhost:端口号:允许脚本请求本地服务(替换成你的Node.js服务实际端口,比如3000)
  2. 获取本地图片并转成base64
    用GM_xmlhttpRequest请求本地图片,将返回的二进制数据转成data:协议的URL——GitHub的CSP允许data:作为图片源。

  3. 插入图片到页面
    创建img元素,将base64 URL赋值给src,再插入到页面指定位置。

完整示例脚本

// ==UserScript==
// @name         加载本地图片到GitHub
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  绕过CSP加载localhost图片
// @match        https://github.com/*
// @grant        GM_xmlhttpRequest
// @connect      localhost:3000  // 替换为你的本地服务端口
// ==/UserScript==

(function() {
    'use strict';

    // 替换为你的本地图片地址
    const localImgUrl = 'http://localhost:3000/test-image.png';

    GM_xmlhttpRequest({
        method: 'GET',
        url: localImgUrl,
        responseType: 'blob',
        onload: function(res) {
            if (res.status !== 200) {
                console.error('加载失败:', res.statusText);
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.style.cssText = 'width:200px; margin:20px;';
                // 插入到页面顶部,可根据需求修改插入位置
                document.body.insertBefore(img, document.body.firstChild);
            };
            reader.readAsDataURL(res.response);
        },
        onerror: function(err) {
            console.error('请求出错:', err);
        }
    });
})();

注意事项

  • 确保本地Node.js服务已启动,图片地址正确,且服务配置了CORS允许跨域请求(比如设置Access-Control-Allow-Origin: *)
  • 若本地服务使用HTTPS,需将URL改为https://localhost:端口号,同时@connect也要对应修改
  • @match指令可根据需要调整,比如只针对GitHub特定页面生效

内容的提问来源于stack exchange,提问作者Phil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:06:28