OLD | NEW |
(Empty) | |
| 1 <!DOCTYPE html> |
| 2 <html> |
| 3 <body> |
| 4 <h1>random</h1> |
| 5 <script src="./random-cached.cgi"></script> |
| 6 <script> |
| 7 const lastRandomNumberKey = "lastRandomNumber"; |
| 8 |
| 9 window.addEventListener("message", e => { |
| 10 if (e.data != "START") { |
| 11 window.opener.postMessage("FAIL: unknown; " + e.data, location.origin); |
| 12 } else { |
| 13 // window.top.randomNumber should be set by random-cached.cgi. |
| 14 if (window.top === undefined || window.top.randomNumber === undefined) { |
| 15 window.opener.postMessage("FAIL: randomNumber isn't defined", |
| 16 location.origin); |
| 17 return; |
| 18 } |
| 19 |
| 20 // If location.reload() is already triggered, lastRandomNumberKey should be |
| 21 // stored in the sessionStorage. Otherwise, this is the first load. |
| 22 const lastRandomNumberString = sessionStorage.getItem(lastRandomNumberKey); |
| 23 if (lastRandomNumberString !== null) { |
| 24 // sessionStorage returns DOMString and need to be converted to Number. |
| 25 const lastRandomNumber = Number(lastRandomNumberString); |
| 26 |
| 27 // Because the random-cached.cgi is a sub-resource, and set HTTP headers |
| 28 // to allow caching, location.reload() should follow the cache-protocol to |
| 29 // reuse the cached resource. That is to say the randomNumber should not |
| 30 // be changed on the reload. |
| 31 window.opener.postMessage(lastRandomNumber == top.randomNumber |
| 32 ? "PASS" |
| 33 : "FAIL: randomNumber was changed", |
| 34 location.origin); |
| 35 } else { |
| 36 // Store the first randomNumber to the sessionStorage, and call reload(). |
| 37 // This window will send "READY" again, then receive "START". |
| 38 sessionStorage.setItem(lastRandomNumberKey, top.randomNumber); |
| 39 location.reload(); |
| 40 } |
| 41 } |
| 42 }, false); |
| 43 |
| 44 // Send "READY" message first so that parent window can ensure to send messages. |
| 45 window.opener.postMessage("READY", location.origin); |
| 46 </script> |
| 47 </body> |
| 48 </html> |
OLD | NEW |