在下面的Stackblitz..。
https://stackblitz.com/edit/it-365-hitpath-pixel-not-firing-through-iframe
我有以下代码:
import React, { Component } from 'react';
import { render } from 'react-dom';
import axios from 'axios';
// Important: before trying this, open a Windows console (not Git Bash or Cygwin) and run the following command:
// > C:\Windows\System32\curl.exe --no-keepalive -H "Authorization: Bearer 1cc6274d5c5837e99f494d732ddf376a" "https://api.pipedream.com/sources/dc_XauVB8/sse"
class App extends Component {
constructor() {
super();
}
handleClick() {
const iframe_str = '<iframe src="https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net" frameborder=0 width=1 height=1></iframe>';
document.getElementById('pixel').innerHTML = iframe_str;
window.top.location.href = 'https://www.google.com/search?q=redirection+done';
}
render() {
const style = {
fontFamily: 'Arial',
backgroundColor: '#afa',
padding: '10px',
}
return (
<div>
<div id="pixel" style={style}>iframe will go here</div><br />
<input type="button" value="Click" onClick={this.handleClick} />
</div>
);
}
}
render(<App />, document.getElementById('root'));我的问题就在这两条线之间:
document.getElementById('pixel').innerHTML = iframe_str;
window.top.location.href = 'https://www.google.com/search?q=redirection+done';我需要访问iframe src上引用的API端点。
在Chrome上,它运行得很好,在重定向之前,iframe被挂载到DOM中,API端点被击中。
但是在Firefox上,线程似乎一点也不等待,甚至在安装iframe和到达API端点之前就尝试重定向。
我通过使用setTimeout并在重定向之前等待1秒来解决这个问题,但是我想知道:
提前感谢!
发布于 2020-09-10 14:05:13
您将始终有一个争用条件,因为您不知道呈现到DOM需要多长时间,并且您也不知道http请求所做的操作。因为它是跨域的,所以您只能使用iframe来判断它已经加载了。
如果端点支持fetch请求,您会更好地处理它。
fetch('https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net', {
mode: 'cors',
cache: 'no-cache'
}).then(() => window.location.href = '//example.com' );或经典img请求
const img = new Image();
const redirectIt = () => window.location.href = '//example.com';
img.onload = redirectIt;
img.onerror = redirectIt;
img.src = 'https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net';或使用sendBeacon
navigator.sendBeacon('https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net');
window.location.href = '//example.com' https://stackoverflow.com/questions/63831128
复制相似问题