如何用Node.js+Puppeteer绕过同源策略并实现无刷新换域名
问题:Puppeteer实现跨域无刷新切换网站URL
我有两个网站mydomain1.com和mydomain2.com,需要用Puppeteer加载第一个网站后,不刷新页面切换到第二个网站的URL。已知浏览器默认禁止这种操作,想通过Node.js操控浏览器实现。
我的浏览器配置如下:
var browser = await puppeteer.launch({ headless: false, executablePath: executable, ignoreDefaultArgs: ["--enable-automation"], args: [ '--disable-web-security', '--disable-features=IsolateOrigins,site-per-process', '--disable-site-isolation-trials', '--disable-features=BlockInsecurePrivateNetworkRequests', '--disable-features=SameSiteByDefaultCookies', '--disable-features=CookiesWithoutSameSiteMustBeSecure', ] });
我的代码如下:
const page = await browser.newPage(); await page.goto('localhost/test.html') await page.evaluate(() => { document.domain = "example.com"; });
运行后出现错误:
Uncaught DOMException: Failed to set the 'domain' property on 'Document': 'example.com' is not a suffix of '127.0.0.1'.
请问是否有办法配置浏览器忽略同源策略?
解决方案
修正
document.domain使用逻辑:document.domain只能设置为当前域名的后缀,比如当前访问localhost(对应127.0.0.1),无法直接设置为example.com——这是浏览器的硬限制,即使禁用web安全也绕不开。必须确保当前页面域名与目标document.domain是后缀关系,比如先访问sub.example.com,再设置document.domain = "example.com"。完善浏览器启动参数:你现有的参数已包含核心的禁用web安全选项,可补充参数强化配置,确保同源策略完全失效:
var browser = await puppeteer.launch({ headless: false, executablePath: executable, ignoreDefaultArgs: ["--enable-automation"], args: [ '--disable-web-security', '--disable-features=IsolateOrigins,site-per-process', '--disable-site-isolation-trials', '--disable-features=BlockInsecurePrivateNetworkRequests', '--disable-features=SameSiteByDefaultCookies', '--disable-features=CookiesWithoutSameSiteMustBeSecure', '--allow-running-insecure-content', // 新增:允许加载非HTTPS内容 '--no-sandbox', // 部分环境下需禁用沙箱才能生效 '--disable-setuid-sandbox' // 配合no-sandbox使用 ] });
- 换无刷新切换思路:如果一定要无刷新切换到不同域名内容,可直接替换页面HTML或用iframe全屏加载目标网站:
- 直接替换页面内容:
const page = await browser.newPage(); await page.goto('https://mydomain1.com'); // 获取目标网站HTML并替换当前页面 const targetHtml = await page.goto('https://mydomain2.com').then(res => res.text()); await page.setContent(targetHtml);- iframe全屏加载:
await page.evaluate((targetUrl) => { const iframe = document.createElement('iframe'); iframe.src = targetUrl; iframe.style.position = 'fixed'; iframe.style.top = '0'; iframe.style.left = '0'; iframe.style.width = '100vw'; iframe.style.height = '100vh'; iframe.style.border = 'none'; document.body.innerHTML = ''; document.body.appendChild(iframe); }, 'https://mydomain2.com');
内容的提问来源于stack exchange,提问作者P. Moy
相关产品推荐
相关产品推荐

