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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM