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

发布于 2024-12-07 17:23:50 字数 68 浏览 0 评论 0原文

我需要从本地文件将名称列表加载到我的 google chrome 扩展中, 这怎么能做到呢?如果文件本身附带扩展名怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她如夕阳 2024-12-14 17:23:50

如果您的扩展程序附带此文件,那么您只需在后台页面内使用 XMLHttpRequest 加载它(使用相对路径,/ 是扩展程序根文件夹)。

您还可以将文件设置为 javascript (var config=[...]),然后使用

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.

五里雾 2024-12-14 17:23:50

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

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

ma​​nifest.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);
  });

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);
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文