原始碼: html

<!DOCTYPE html>
<html>
<body>

<iframe id="result"></iframe>  

<script>
const Http = new XMLHttpRequest();
//const url='https://jsonplaceholder.typicode.com/posts';
const url='https://www.nkust.edu.tw';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
  //console.log(Http.responseText)
  html=Http.responseText;
result.contentWindow.document.open();
result.contentWindow.document.write(html);
result.contentWindow.document.close();  
}
</script>

</body>
</html>

📝 更改程式碼中的url: http://www2.nkust.edu.tw/~linchao/Javascript/2021/web.html

NO:

Cross-Origin Resource Sharing(CORS),跨來源資源共享。

瀏覽器因為安全性的考量,提出同源政策(Same-origin policy)觀念。

意思就是說如果索取的網頁和我們所在的網頁不再同一個位址的時候(包含在「不同源」的觀念裡面),瀏覽器雖然仍然發 Request,但是會把 Response 給拒絕(是瀏覽器拒絕),此時 JavaScript 拿到錯誤訊息。

什麼是不同源呢? 最簡單的講法就是,Domain不一樣就是不同源、一個用http一個用https、或是端口號不一樣,都是不同源。

這套規範說,如果想開啟跨來源 HTTP 請求的話,Server 必須在 Response 的 Header 裡面加上Access-Control-Allow-Origin(line #5)。

Content-Type: application/json
Content-Length: 71
Connection: keep-alive
Server: nginx
Access-Control-Allow-Origin: * 🏷
Cache-Control: no-cache, no-store, must-revalidate, private
Expires: 0
...

上面的第5行

When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default. Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.

輔助

dynamic iframe

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();