我想创建chrome扩展名,该扩展名将能够读取本地文件并使用在其中写入的代码。我的简单代码是:
const readFile = (filePath) => {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest()
xhr.onerror = (error) => {
reject(error)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
resolve(xhr.response)
}
}
xhr.ontimeout = function () {
reject('timeout')
}
xhr.open('GET', filePath)
xhr.send()
})
}
async function () {
const code = await readFile(jsFilePath)
console.log(code)
}
Run Code Online (Sandbox Code Playgroud)
当我的filePath正确时,此代码成功工作。但是如果不是,Chrome控制台会抛出此错误:
GET file:///home/maxim/Documents/test.jsa net::ERR_FILE_NOT_FOUND
Run Code Online (Sandbox Code Playgroud)
通常的try / catch块不起作用
async function () {
try {
const code = await readFile(jsFilePath)
console.log(code) …Run Code Online (Sandbox Code Playgroud)