Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access local files through Google chrome extension?

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?

like image 998
Max Avatar asked Oct 01 '11 17:10

Max


People also ask

Can a Chrome extension access local files?

For security reasons, by default the Chrome browser does not allow extensions to access local files. If you want the accelerator to access local files (locations of "file:///...", instead of "http://" or "https://"), you must configure Chrome to allow the access.

Can browser access local files?

Web browsers (and JavaScript) can only access local files with user permission. To standardize file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.


2 Answers

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.

like image 95
serg Avatar answered Oct 08 '22 03:10

serg


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);
  });
like image 20
Rohit Nandi Avatar answered Oct 08 '22 05:10

Rohit Nandi