通过谷歌Chrome扩展访问本地文件?

ev7lccsx  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(473)

我需要从本地文件加载一个名称列表到我的谷歌Chrome扩展,如何才能做到这一点?如果文件附带扩展名本身会怎么样?

gdrx4gfi

gdrx4gfi1#

如果此文件随扩展名一起提供,那么您可以在后台页面中使用XMLHttpRequest加载它(使用相对路径,/是扩展根文件夹)。
您也可以将您的文件设置为JavaScript(var config=[...]),然后将其与<script>一起加载到后台页面。

wkyowqbh

wkyowqbh2#

假设您的json文件是以下文件夹中的names.json

-- manifest.json
-- config
   |-- names.json

manifest.json中添加资源路径

"web_accessible_resources": [
        "config/names.json"
    ]

使用**fectch()* API访问资源

const url = chrome.runtime.getURL('./config/names.json');

fetch(url)
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

相关问题