如果没有任何服务器端解决方案,安全页面只有一种方式可以从不安全的页面/请求中获取信息,这就是 postMessage 和弹出窗口
我说弹出窗口是因为该网站不允许混合内容。但是弹出窗口并没有真正混合。它有自己的窗口,但仍然可以通过 postMessage 与开启者通信。
因此,您可以使用 window.open(...) 打开一个新的 http 页面并让该页面为您发出请求
XDomain 是我写这篇文章的时候想到的,但这是一种使用新 fetch api 的现代方法,优点是大文件的流式传输,缺点是它不适用于所有浏览器
您将此代理脚本放在任何 http 页面上
onmessage = evt => {
const port = evt.ports[0]
fetch(...evt.data).then(res => {
// the response is not clonable
// so we make a new plain object
const obj = {
bodyUsed: false,
headers: [...res.headers],
ok: res.ok,
redirected: res.redurected,
status: res.status,
statusText: res.statusText,
type: res.type,
url: res.url
}
port.postMessage(obj)
// Pipe the request to the port (MessageChannel)
const reader = res.body.getReader()
const pump = () => reader.read()
.then(({value, done}) => done
? port.postMessage(done)
: (port.postMessage(value), pump())
)
// start the pipe
pump()
})
}
然后您在 https 页面中打开一个弹出窗口(请注意,您只能在用户交互事件中执行此操作,否则它将被阻止)
window.popup = window.open(http://.../proxy.html)
创建你的实用函数
function xfetch(...args) {
// tell the proxy to make the request
const ms = new MessageChannel
popup.postMessage(args, '*', [ms.port1])
// Resolves when the headers comes
return new Promise((rs, rj) => {
// First message will resolve the Response Object
ms.port2.onmessage = ({data}) => {
const stream = new ReadableStream({
start(controller) {
// Change the onmessage to pipe the remaning request
ms.port2.onmessage = evt => {
if (evt.data === true) // Done?
controller.close()
else // enqueue the buffer to the stream
controller.enqueue(evt.data)
}
}
})
// Construct a new response with the
// response headers and a stream
rs(new Response(stream, data))
}
})
}
然后像平常一样使用 fetch api 发出请求
xfetch('http://httpbin.org/get')
.then(res => res.text())
.then(console.log)