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

无远程网站修改权限时,如何获取其<head>内容并解决CORS拦截?

解决Chrome扩展跨域获取远程网站内容的方案

因为你是在Chrome扩展环境下,直接在popup中发起跨域请求会被CORS拦截,但利用扩展的后台服务工作者(Service Worker)可以绕过这个限制——只要manifest中配置了对应的host_permissions,后台脚本不受CORS策略约束。

具体实现步骤:

  1. 更新manifest.json
    添加后台服务工作者的配置,确保已声明<all_urls>的主机权限:

    {
      "manifest_version": 3,
      "version": "0.0.5",
      "action": {
        "default_popup": "popup/popup.html"
      },
      "permissions": ["activeTab", "scripting"],
      "host_permissions": ["<all_urls>"],
      "background": {
        "service_worker": "background.js"
      }
    }
    
  2. 编写后台脚本background.js
    负责接收popup的请求,发起跨域请求并提取内容:

    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.action === 'getHeadContent') {
        // 模拟浏览器请求头,避免被目标网站反爬拦截
        fetch(request.url, {
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
          }
        })
        .then(response => {
          if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
          return response.text();
        })
        .then(html => {
          const parser = new DOMParser();
          const doc = parser.parseFromString(html, 'text/html');
          sendResponse({ success: true, headContent: doc.head.innerHTML });
        })
        .catch(error => {
          sendResponse({ success: false, errorMsg: error.message });
        });
        // 返回true表示异步响应
        return true;
      }
    });
    
  3. 修改popup中的请求逻辑
    替换原有的httpGet函数,通过消息通信调用后台脚本:

    function getRemoteHead(url) {
      chrome.runtime.sendMessage(
        { action: 'getHeadContent', url: url },
        (response) => {
          if (response.success) {
            console.log('获取到的<head>内容:', response.headContent);
            // 此处处理获取到的head内容
          } else {
            console.error('请求失败:', response.errorMsg);
          }
        }
      );
    }
    
    // 使用示例
    // getRemoteHead('https://www.youtube.com');
    

注意事项:

  • 避免使用同步XMLHttpRequest(你的原代码中open的第三个参数为false),现代浏览器已不推荐同步请求,且扩展环境下可能引发性能问题。
  • 部分网站会有反爬机制,需要模拟合法的请求头(如User-Agent)才能成功获取内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:14:56