You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重构箭头函数以兼容IE?验证码监听脚本改造问询

解决IE兼容问题:重构验证码检测脚本中的箭头函数

IE确实不支持ES6的箭头函数,而且还有个容易忽略的细节——String.prototype.includes也在IE里跑不起来,咱们一步步把这两处问题代码重构好,让脚本在IE中正常工作:

1. 重构iframe查找的代码段

原来的find回调箭头函数有两个IE兼容坑:

  • 箭头函数语法不被IE支持,要换成传统的function写法
  • includes方法在IE中不存在,得用indexOf !== -1来替代字符串匹配逻辑

修改后的代码如下:

.find(function(x) {
  return x.src.indexOf('google.com/recaptcha/api2/bframe') !== -1;
})

后面的.parentNode.parentNode可以直接保留,这部分IE是完全支持的。

2. 重构MutationObserver的回调函数

同样把这里的箭头函数换成普通函数,同时把原来的短路表达式拆成清晰的条件判断,可读性更好,也更适配IE的执行逻辑:

new MutationObserver(function(x) {
  if (recaptchaWindow.style.opacity == 0) {
    onClose();
  }
})

完整的重构后脚本

把两处修改整合到原代码中,最终兼容IE的版本是:

function initListener() {
  // set a global to tell that we are listening
  window.recaptchaCloseListener = true;
  // find the open reCaptcha window
  HTMLCollection.prototype.find = Array.prototype.find;
  var recaptchaWindow = document
    .getElementsByTagName('iframe')
    .find(function(x) {
      return x.src.indexOf('google.com/recaptcha/api2/bframe') !== -1;
    })
    .parentNode.parentNode;
  // and now we are listening on CSS changes on it
  // when the opacity has been changed to 0 we know that
  // the window has been closed
  new MutationObserver(function(x) {
    if (recaptchaWindow.style.opacity == 0) {
      onClose();
    }
  }).observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] });
}

内容的提问来源于stack exchange,提问作者Sean Doherty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:02:14