通过Google Chrome扩展程序访问本地文件?

Max*_*Max 7 google-chrome local-storage google-chrome-extension

我需要从本地文件中将名称列表加载到我的谷歌浏览器扩展程序中,如何做到这一点?如果文件附带扩展本身怎么办?

ser*_*erg 5

如果此文件随扩展程序一起提供,那么您只需XMLHttpRequest在内部背景页面中加载它(使用相对路径,/作为扩展根文件夹).

您还可以将文件设置为javascript(var config=[...]),然后将其加载<script>到后台页面中.


Roh*_*ndi 5

假设你的json文件是names.json,位于以下文件夹中

-- manifest.json
-- config
   |-- names.json
Run Code Online (Sandbox Code Playgroud)

manifest.json中添加资源路径

"web_accessible_resources": [
        "config/names.json"
    ]
Run Code Online (Sandbox Code Playgroud)

使用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);
  });
Run Code Online (Sandbox Code Playgroud)