So the XMLHttpRequest shouldn't work for loading local files for websites. It would be a crazy security risk if a person could actually gain access to a user's file system via JavaScript.
But for whatever reason when I use a XMLHttpRequest to load a local text file in a chrome extension it works. Why is it that when I use XMLHttpRequest for a chrome extension in the background script it loads the file? Is this a security flaw or is it intentional? And doesn't this create similar security risks as having the request load local files in a web-page?
Let me try to explain this in the best way I can:
I have a text file called abc.txt
and I want to open it and read the file contents via JavaScript so I decided to use an XMLHttpRequest.
<!DOCTYPE html>
<html>
<body>
<script>
</script>
<script>
let txt = '';
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
console.log(txt)
}
};
xmlhttp.open("GET", "abc.txt", true);
xmlhttp.send();
</script>
</body>
</html>
I get the usual error, test.html:17 Failed to load file:///C:/Users/none/of/your/business/abc.txt: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
However when I make a chrome extension I can load the local file via the background.js script.
manifest.js file:
{
"name": "Question",
"version": "1.0",
"manifest_version": 2,
"background": {
"persistent": true,
"scripts":["background.js"]
}
}
background.js file:
chrome.runtime.onInstalled.addListener(function() {
let txt = '';
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
console.log(txt)
}
};
xmlhttp.open("GET", "abc.txt", true);
xmlhttp.send();
});
proof that text file is loaded:
To restate my question, why does XMLHttpRequests treat the chrome extension's background.js script differently? Does't it create similar problems as having XMLHttpRequests on a web page?
NOTE: The XMLHttpRequest only seems to only work in the background.js file, the minute I link the file to a HTML document it stops functioning and I get the normal error message. So I can't run it on the popup html file.
正如Deliaz所说,答案是chrome允许CORS请求。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.