我正在使用
page.SetContentAsync(myHtml);
Puppeteer Sharp 中的方法加载一些未托管在任何服务器上的 HTML。
不幸的是,在我的 HTML 中我需要使用一个 JS 脚本(我不能轻易修改),它依赖于 location.pathname
值包含至少一个斜杠 /
(它对其进行一些解析),否则它会崩溃。
有没有办法,通过 Puppeteer 本身或简单的 JavaScript,覆盖/伪造 location.pathname
的值?
最佳答案
您可以使用 --disable-web-security
禁用同源策略然后使用 history.replaceState()
替换浏览器历史记录中的当前条目。
这将更改 location.pathname
的值,而不会导致页面重定向。
考虑以下示例:
'use strict';
const puppeteer = require( 'puppeteer' );
( async () =>
{
const browser = await puppeteer.launch({
'args' : [
'--disable-web-security'
]
});
const page = await browser.newPage();
let pathname = await page.evaluate( () =>
{
const fake_pathname = '/example/index.php';
history.replaceState( null, null, 'http://_' + fake_pathname );
return location.pathname;
});
console.log( pathname ); // /example/index.php
await page.setContent( /* ... */ );
// Perform your task ...
await browser.close();
})();
关于javascript - puppeteer 师夏普 : setting a fake path when loading content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882504/