iT邦幫忙

0

jQuery load 本地tml檔案

Zaku 2016-11-19 17:17:0515777 瀏覽
  • 分享至 

  • xImage

各位好,想請問一下如果不透過後台,直接用jquery的load去讀取本地的html檔案似乎會有安全問題,不給load,是否有什麼解法?

列如:
$("#thediv").load("index.html");

會有下列錯誤資訊:

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
看更多先前的討論...收起先前的討論...
jsgao0 iT邦新手 5 級 ‧ 2016-11-21 11:48:31 檢舉
瀏覽器會有CORS的限制。 你試試看用完整的網址(domain & port必須和你當前頁面相同)。
Zaku iT邦新手 3 級 ‧ 2016-11-21 13:32:24 檢舉
在同一個資料夾之下,若不透過後台僅用前台操作,無法用domain & port?
jsgao0 iT邦新手 5 級 ‧ 2016-11-21 14:58:17 檢舉
因為local file system的domain是null,可參考這篇說明: https://eureka.ykyuen.info/2013/09/24/chrome-bypass-access-control-allow-origin-on-local-file-system/

另外,若你真的要load file,你可以嘗試將html用iframe載入,再用element selector去找到它。
Zaku iT邦新手 3 級 ‧ 2016-11-21 15:08:10 檢舉
我發現火狐沒有這樣的限制?
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
jsgao0
iT邦新手 5 級 ‧ 2016-11-22 09:19:39

先從RFC文件開始說起吧!

This document defines the concept of an "origin", which is often used
as the scope of authority or privilege by user agents. Typically,
user agents isolate content retrieved from different origins to
prevent malicious web site operators from interfering with the
operation of benign web sites. In addition to outlining the
principles that underlie the concept of origin, this document details
how to determine the origin of a URI and how to serialize an origin
into a string. It also defines an HTTP header field, named "Origin",
that indicates which origins are associated with an HTTP request.

從這段話可以知道,做origin的管理是為了安全性考量。 舉裡來說,有人偷偷改了jQuery的來源(http://i.am.jQuery),在ajax發送的同時,將你頁面的密碼資訊傳到了他自己的server(http://i.am.a.bad.guy)。 詳細的說明,請詳閱文件。

回到正題: 本地的檔案是否可以用JavaScript讀取? 來看一下文件的說明吧!

  1. If uri-scheme is "file", the implementation MAY return an
    implementation-defined value.
    NOTE: Historically, user agents have granted content from the
    file scheme a tremendous amount of privilege. However,
    granting all local files such wide privileges can lead to
    privilege escalation attacks. Some user agents have had
    success granting local files directory-based privileges, but
    this approach has not been widely adopted. Other user agents
    use globally unique identifiers for each file URI, which is
    the most secure option.

上面說得很清楚,雖然檔案位在同個目錄,但還沒廣泛被user agent採用。 Firefox預設也是會確認的,我不清楚你為什麼說沒這樣的限制。

Zaku iT邦新手 3 級 ‧ 2016-11-28 15:07:08 檢舉

我也不清楚呢,因為我用火狐開起確實是可以順利的load到檔案...
因jQuery確實是可以讓你不透過後台就load網頁檔案近來,如果瀏覽器都不給你用,那這功能的一部分不就有點弔詭?

我要發表回答

立即登入回答