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

Manifest V3 Chrome扩展未刷新页面无法启动问题求助

解决方案

1. 更新manifest.json

把内容脚本的匹配范围扩大到整个vk.com,这样脚本会注入到所有VK页面,后续在脚本内判断当前URL是否符合目标条件:

{
    "manifest_version": 3,
    "name": "Target",
    "description": "Target Features",
    "version": "1.0",

    "action": {
      "default_icon": "icon.png"
    },
  
    "content_scripts": [
      {
        "matches": [
          "https://vk.com/*"
        ],
        "js": ["script.js"]
      }
    ],

    "permissions": [
      "storage"
    ]
  }

2. 重写script.js实现URL监听与内容管理

VK是单页应用(SPA),站内跳转不会刷新页面,所以需要主动监听URL变化,同时处理内容的创建和销毁:

// 目标页面URL的正则匹配
const TARGET_URL = /^https:\/\/vk\.com\/target$/;

// 目标方块实例
let targetBlock = null;

// 创建方块
function createBlock() {
  targetBlock = document.createElement('div');
  Object.assign(targetBlock.style, {
    width: '100px',
    height: '100px',
    backgroundColor: 'white',
    position: 'fixed',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)'
  });
  document.body.appendChild(targetBlock);
}

// 移除方块
function removeBlock() {
  if (targetBlock?.parentNode) {
    targetBlock.parentNode.removeChild(targetBlock);
    targetBlock = null;
  }
}

// 根据当前URL更新方块状态
function syncBlockWithUrl() {
  if (TARGET_URL.test(window.location.href)) {
    !targetBlock && createBlock();
  } else {
    removeBlock();
  }
}

// 监听浏览器前进/后退
window.addEventListener('popstate', syncBlockWithUrl);

// 监听SPA常用的history跳转(pushState/replaceState不会触发popstate)
const originalPushState = history.pushState;
history.pushState = (...args) => {
  originalPushState.apply(history, args);
  syncBlockWithUrl();
};

const originalReplaceState = history.replaceState;
history.replaceState = (...args) => {
  originalReplaceState.apply(history, args);
  syncBlockWithUrl();
};

// 监听DOM变化(部分SPA通过修改DOM切换页面,作为补充)
const domObserver = new MutationObserver(() => syncBlockWithUrl());
domObserver.observe(document.documentElement, {
  childList: true,
  subtree: true,
  attributes: true
});

// 页面初始加载时检查URL
syncBlockWithUrl();

核心逻辑说明

  • 扩大匹配范围:让脚本在所有VK页面注入,才能监听全站的URL变化。
  • 捕获SPA跳转:重写history.pushState和history.replaceState,因为这两个方法是SPA站内跳转的常用方式,不会触发默认的popstate事件。
  • DOM监听兜底:部分SPA可能通过修改DOM结构来切换页面内容,监听DOM变化可以确保URL变化时及时响应。
  • 内容生命周期管理:封装创建和移除方块的函数,切换页面时及时清理DOM,避免冗余元素和内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:55:09