加载存储在 chrome 扩展中的资产 [英] Loading an asset stored within a chrome extension

查看:23
本文介绍了加载存储在 chrome 扩展中的资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在名为 settings.json 的扩展中存储了一个 JSON 文件.我可以使用以下方法获取文件的 URL:

Let's say I have a JSON file stored within my extension called settings.json. I can get the URL of the file using:

chrome.extension.getURL("settings.json");

但是现在我有了 URL,我如何实际加载该文件的内容,以便我可以 JSON.parse 并使用它?我这样做的原因是有一个服务器组件,我想让在多个服务器上的部署和测试更容易(开发、登台、生产等).或者,如果有一种方法可以将自定义属性添加到清单.json 并访问它们,这也可以.

But now that I have the URL, how do I actually load the contents of that file so I can JSON.parse it and use it? The reason I'm doing this is that there is a server component, and I want to make deployment and testing on multiple servers easier (dev, staging, production, etc.) Alternatively if there's a way to add custom attributes to the manifest.json and access them, that would also work.

推荐答案

如果你让你的 setting.js 看起来像:

If you make your setting.js look like:

var settings =  {"param":value,...};

然后您可以将其包含在后台页面中并使用设置变量:

Then you can just include it on a background page and use settings variable:

<script src="settings.js"></script>

如果你想在你的文件中包含纯 json 而不将它分配给任何变量,那么你可以使用 XMLHttpRequest 加载它:

If you want to have pure json in your file without assigning it to any variables then you can load it using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
xhr.open("GET", chrome.extension.getURL('/config_resources/config.json'), true);
xhr.send();

或者如果您在项目中包含了 jquery:

or if you included jquery into your project:

$.getJSON(chrome.extension.getURL('/config_resources/config.json'), function(settings) {
  //..
});

(顺便说一句,仅当您从内容脚本访问文件时才需要使用 chrome.extension.getURL,否则您可以只使用相对路径 /config_resources/config.json)

(btw using chrome.extension.getURL is required only if you are accessing a file from a content script, otherwise you can just use relative path /config_resources/config.json)

这篇关于加载存储在 chrome 扩展中的资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆