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

Microsoft Edge扩展异常:重定向时获取图片URL而非页面URL

问题分析与解决

问题原因

你的扩展通过chrome.webRequest.onBeforeRequest监听http://abcd/*下的所有请求,但这个API会捕获该域名下所有类型的网络请求——包括页面HTML主文档、图片、CSS、JS等静态资源。当原页面加载缓慢时,页面中的jpg图片请求可能先于HTML主文档请求触发监听,此时Cookie还未设置,代码会误将图片URL当作原页面URL执行重定向,从而出现异常。

解决方案

1. 仅处理主文档请求

在webRequest监听配置中添加types: ["main_frame"],只对用户实际访问的页面主文档请求做处理,直接忽略静态资源的请求。

2. 优化Cookie作用域

将Cookie的url设置为站点根域名(比如http://abcd/),确保整个站点的请求都能正确读取该Cookie,避免因资源路径不同导致的Cookie判断错误。

3. 编码跳转参数

对原页面URL做encodeURIComponent编码,避免URL中的特殊字符破坏重定向链接的参数结构。

修改后的代码

//background.js
const apps = [    
  ['ABCD', 'abcd']
];
const triggerUrls = [
  "http://abcd/*"
];  

function logURL(requestDetails) {
  // 跳过非主文档的请求
  if (requestDetails.type !== 'main_frame') return;

  const domain = (new URL(requestDetails.url)).hostname.replace('www.','').toLowerCase();
  const partDomain = apps.findIndex(u => domain.toUpperCase().split('.')[0].includes(u[0]));
  
  // 设置Cookie到站点根域名,确保作用域覆盖整个站点
  const cookieRootUrl = `http://${domain.split('.').slice(-2).join('.')}/`;
  
  chrome.cookies.get({ 'url': cookieRootUrl, 'name': 'status' }, 
    function(data){         
      if (data === null) {                                
        if (partDomain > -1) {
          chrome.cookies.set({
            url: cookieRootUrl,
            name: "status",
            value: "opened"
          });
          const backUrl = encodeURIComponent(requestDetails.url);
          const url = `http://warning.xx/?title=${apps[partDomain][0]}&url=${backUrl}`;
          chrome.tabs.update(requestDetails.tabId, { url: url} );
        }
      }
    }   
  );  
}

chrome.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: triggerUrls, types: ["main_frame"]}, // 仅监听主文档请求
  ["blocking"]
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:20:59