【发布时间】:2014-12-10 00:01:21
【问题描述】:
为了在服务器上的 dev/stage/prod 之间切换,我设置了一个 ENV 变量。这是相当标准的。
使用离线 Chrome 应用程序,我如何在 dev/stage/prod 之间切换?尤其是在 REST API URL 周围?
在开发过程中,我的应用作为“解包”应用安装在 chrome 中。
解决方案:
我结合了这些答案。这是我所做的:
安装时,如果解压扩展,我在 localStorage 中设置一个值。
在应用运行时,我将变量设置为本地存储值,如果未定义,则设置为生产环境。
FWIW,这是代码:
background.js:
chrome.runtime.onInstalled.addListener(function () {
console.log('onInstalled');
// Note: this event is fired every time the "Reload" link is clicked in
// 'Chrome Apps & Extensions Developer Tool'. So only set if not set.
// If unpacked extension,
if(!chrome.runtime.getManifest().update_url) {
// Load existing value
chrome.storage.local.get('APIBaseURL', function(data) {
// Has value already been set?
if (!data.hasOwnProperty('APIBaseURL')) {
// set API server to localhost
chrome.storage.local.set({'APIBaseURL': DEV_APIBASEURL }, function() {
// Ok, notify the console.
console.log('Installed in dev mode: APIBaseURL = '+DEV_APIBASEURL);
} );
}
});
}
});
App.js(这是 Angular,但你应该看到模式。Promise 是 ES6)
var PROD_APIBASEURL = 'https://production.com';
angular.module('wmw', ['wmw.routes'])
// Listen for online/offline events and set status in $rootScope
.run(['$rootScope', function($rootScope){
// Determine which server to run on
$rootScope.isDev = chrome.runtime.getManifest().hasOwnProperty('update_url');
// Async init code is in a Promise
$rootScope.promiseAppReady = new Promise(function(resolve, reject) {
// Get the Base URL
chrome.storage.local.get('APIBaseURL', function(data) {
// Apply it to our scope. If not set, use PROD.
$rootScope.$apply(function() {
if (data.hasOwnProperty('APIBaseURL')) {
$rootScope.APIBaseURL = data.APIBaseURL;
} else {
$rootScope.APIBaseURL = PROD_APIBASEURL;
}
resolve($rootScope.APIBaseURL);
});
});
});
}]);
$rootScope.promiseAppReady 让我知道代码何时完成并且应用程序准备就绪。
$rootScope.$apply() 气泡更改为其他范围。如果你不使用 Angular,你可以删除它。
我还将这段代码包含在一些调试工具中:
var debugTools = {
setAPIBaseURL: function (url) {
chrome.storage.local.set({'APIBaseURL': url});
},
showAPIBaseURL: function() {
chrome.storage.local.get('APIBaseURL', function(data) {console.log(data)});
}
}
所以很容易在控制台中更改。
【问题讨论】:
-
Chrome 应用程序不是 Chrome 扩展程序。你没有帮助。
-
@MichaelCole 一些答案适用于扩展程序和应用程序。至于没有帮助,请保持问答格式:编辑您的问题以删除解决方案,并将其作为另一个答案发布。
-
@xan,我发现 StackOverflow 非常过度修改。很抱歉冒犯了你。
标签: angularjs google-chrome-extension google-chrome-devtools google-chrome-app cordova-chrome-app