js杂项积累

一 浏览器重定向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>
posted @ 2018-10-28 11:49  拿饭盒当烟灰缸  阅读(873)  评论(0编辑  收藏  举报