首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Firefox上,当请求将iframe装入DOM时,线程在等待安装iframe之前继续执行下一个指令。

在Firefox上,当请求将iframe装入DOM时,线程在等待安装iframe之前继续执行下一个指令。
EN

Stack Overflow用户
提问于 2020-09-10 13:48:52
回答 1查看 207关注 0票数 0

在下面的Stackblitz..。

https://stackblitz.com/edit/it-365-hitpath-pixel-not-firing-through-iframe

我有以下代码:

代码语言:javascript
复制
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'));

我的问题就在这两条线之间:

代码语言:javascript
复制
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秒来解决这个问题,但是我想知道:

  1. 有更好的方法吗?
  2. 为什么这个问题会发生在Firefox而不是Chrome上呢?

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-10 14:05:13

您将始终有一个争用条件,因为您不知道呈现到DOM需要多长时间,并且您也不知道http请求所做的操作。因为它是跨域的,所以您只能使用iframe来判断它已经加载了。

如果端点支持fetch请求,您会更好地处理它。

代码语言:javascript
复制
fetch('https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net', {
  mode: 'cors',
  cache: 'no-cache'
}).then(() => window.location.href = '//example.com' );

或经典img请求

代码语言:javascript
复制
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

代码语言:javascript
复制
navigator.sendBeacon('https://93b9e1b4bc322adcd6d208d483bf0c9a.m.pipedream.net');
window.location.href = '//example.com' 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63831128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档