https ajax error,javascript - HTTP Ajax Request via HTTPS Page - Stack Overflow

Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you

XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

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()

})

}

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

window.popup = window.open(http://.../proxy.html)

create your utility function

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))

}

})

}

And make the request like you normally do with the fetch api

xfetch('http://httpbin.org/get')

.then(res => res.text())

.then(console.log)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值