js杂项积累

本文深入探讨了前端开发中常见的技巧与潜在陷阱,包括浏览器重定向的跨域问题、HTML select标签的多选属性、document.write的正确用法、JS操作新窗口的限制以及iframe与父窗口间的对象独立性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 浏览器重定向Http请求跨域

重定向第一次请求跨域,仍可以发送第二次请求
第二次请求服务器端可正常运行,客户端将无法接受到数据。

如下是遇到此问题时的一些可以观察到的表现:

  1. 浏览器的开发页的network标签页中,http请求无异常,能在preview中看到结果。
  2. 浏览器会在console里报出跨域错误。
  3. 处理跨域请求结果的js因报错而终止执行。

二 html select标签 可以设置属性multipe,变为多选

<select multipe id="s" name="s">
  <option value="1">1</option>
  <option value="2">2</option>
</select>
s.onchange = function () {
  console.log(Array.prototype.map.call(this.options, (item) => {
    return return item.value + 'is selected: ' + item.selected
  }).join('\n'))
}

三 document.wirte只应在script标签的顶层代码中使用。不能放在函数的定义中,否则原有文档将被清空。

<script>
  document.write("写在顶层,这样脚本在解析阶段就会执行!") // ok
  document.documentElement.onclick = () => {
    document.write('点击了页面,调用write写入新内容,原有内容将被清空')
  }
</script>

四 js可以打开一个新窗口,如果符合同源策略要求,可以访问新窗口的window对象。js如果要关闭一个不是通过js打开的窗口,则需要一些特殊的技巧

以下代码展示了如何关闭当前浏览页面:

const closeWebPage = () => {
  if (navigator.userAgent.indexOf('MSIE') > 0) {
    if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
      window.opener = null
      window.close()
    } else {
      window.open('', '_top')
      window.top.close()
    }
  } else if (navigator.userAgent.indexOf('Firefox') > 0 || navigator.userAgent.indexOf('Chrome') > 0) {
    window.location.href = 'about:blank'
    window.close()
  } else {
    window.opener = null
    window.open('', '_self')
    window.close()
  }
}

五 多个窗口(浏览器窗口)和多个iframe窗体之间的原型对象、类都互相独立

父页面:

<body>
  <iframe src="./frame.html" frameborder="0" id="frame"></iframe>
</body>
<script>
  var p = Object.prototype
  var o = Object
</script>

内嵌页面frame:

<body>
  frame content
</body>
<script>
  var frameP = Object.prototype
  console.log(frameP) // {constructor: ƒ, __defineGetter__: ƒ, …}
  var parentP = window.parent.p
  console.log(parentP) // {constructor: ƒ, __defineGetter__: ƒ, …}
  console.log(frameP === parentP) // false
  
  var frameO = Object
  console.log(frameO) // ƒ Object() { [native code] }
  var parentO = window.parent.o
  console.log(parentO) // ƒ Object() { [native code] }
  console.log(frameO === parentO) // false
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值