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

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

问题描述

假设我的扩展名中存储了名为settings.json的JSON文件。我可以使用这个文件的URL:

  chrome.extension.getURL(settings.json); 

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

解决方案

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

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

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

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

如果您希望在文件中使用纯JSON而不将其分配给任何变量,那么您可以加载它使用XMLHttpRequest:

  var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = handleStateChange; //在其他地方实施。
xhr.open(GET,chrome.extension.getURL('/ config_resources / config.json'),true);
xhr.send();

或者如果您将jquery包含到您的项目中:

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



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


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");

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.

解决方案

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>

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();

or if you included jquery into your project:

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

(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天全站免登陆