开发者

Access local files through Google chrome extension?

开发者 https://www.devze.com 2023-04-10 03:58 出处:网络
I need to load a list of names into my google chrome extension 开发者_高级运维from a local file,

I need to load a list of names into my google chrome extension 开发者_高级运维from a local file, How can this be done? what if the file is shipped with the extension itself?


If this file is shipped with your extension then you can just load it with XMLHttpRequest inside background page (use relative paths, with / being extension root folder).

You can also make your file to be javascript (var config=[...]) and just load it with <script> into background page.


Say your json file is names.json in the following folder

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

In manifest.json add path to the resource

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

Use fectch() API to access the resource

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);
  });
0

精彩评论

暂无评论...
验证码 换一张
取 消