Javascript 如何自动重新加载我正在开发的 Chrome 扩展程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2963260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I auto-reload a Chrome extension I'm developing?
提问by Andrey Fedorov
I'd like for my chrome extension to reload every time I save a file in the extension folder, without having to explicitly click "reload" in chrome://extensions/. Is this possible?
我希望每次在扩展文件夹中保存文件时,我的 chrome 扩展都会重新加载,而无需在 chrome://extensions/ 中明确单击“重新加载”。这可能吗?
Edit: I'm aware I can update the intervalat which Chrome reloads extensions, which is a half-way solution, but I'd rather either making my editor (emacs or textmate) trigger on-save a reload or asking Chrome to monitor the directory for changes.
编辑:我知道我可以更新Chrome 重新加载扩展程序的间隔,这是一个半途而废的解决方案,但我宁愿让我的编辑器(emacs 或 textmate)触发保存重新加载或要求 Chrome 进行监控更改的目录。
采纳答案by Arik
You can use "Extensions Reloader"for Chrome:
您可以使用“扩展Reloader”Chrome浏览器:
Reloads all unpacked extensions using the extension's toolbar button or by browsing to "http://reload.extensions"
If you've ever developed a Chrome extension, you might have wanted to automate the process of reloading your unpacked extension without the need of going through the extensions page.
"Extensions Reloader" allows you to reload all unpacked extensions using 2 ways:
1 - The extension's toolbar button.
2 - Browsing to "http://reload.extensions".
The toolbar icon will reload unpacked extensions using a single click.
The "reload by browsing" is intended for automating the reload process using "post build" scripts - just add a browse to "http://reload.extensions" using Chrome to your script, and you'll have a refreshed Chrome window.
使用扩展的工具栏按钮或浏览到“ http://reload.extensions”重新加载所有解压的扩展
如果您曾经开发过 Chrome 扩展程序,您可能希望无需浏览扩展程序页面即可自动重新加载解压扩展程序的过程。
“扩展重新加载器”允许您使用 2 种方式重新加载所有解压的扩展:
1 - 扩展的工具栏按钮。
2 - 浏览到“ http://reload.extensions”。
工具栏图标将通过单击重新加载解压的扩展。
“通过浏览重新加载”旨在使用“后构建”脚本自动执行重新加载过程 - 只需在脚本中使用 Chrome添加对“ http://reload.extensions”的浏览,您将拥有一个刷新的 Chrome 窗口。
Update:As of January 14, 2015, the extension is open-sourced and available on GitHub.
更新:截至 2015 年 1 月 14 日,该扩展已开源并可在 GitHub 上获得。
回答by Rob W
Update: I have added an options page, so that you don't have to manually find and edit the extension's ID any more. CRXand source code are at: https://github.com/Rob--W/Chrome-Extension-Reloader
Update 2: Added shortcut (see my repository on Github).
The original code, which includes the basic functionalityis shown below.
更新:我添加了一个选项页面,这样您就不必再手动查找和编辑扩展程序的 ID。CRX和源代码位于:https: //github.com/Rob--W/Chrome-Extension-Reloader
更新 2:添加了快捷方式(请参阅我在 Github 上的存储库)。
包含基本功能的原始代码如下所示。
Create an extension, and use the Browser Actionmethod in conjunction with the chrome.extension.managementAPI to reload your unpacked extension.
创建一个扩展,并结合使用浏览器操作方法和chrome.extension.managementAPI 来重新加载解压后的扩展。
The code below adds a button to Chrome, which will reload an extension upon click.
下面的代码向 Chrome 添加了一个按钮,点击后将重新加载扩展程序。
manifest.json
manifest.json
{
"name": "Chrome Extension Reloader",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts": ["bg.js"] },
"browser_action": {
"default_icon": "icon48.png",
"default_title": "Reload extension"
},
"permissions": ["management"]
}
bg.js
bg.js
var id = "<extension_id here>";
function reloadExtension(id) {
chrome.management.setEnabled(id, false, function() {
chrome.management.setEnabled(id, true);
});
}
chrome.browserAction.onClicked.addListener(function(tab) {
reloadExtension(id);
});
回答by Leonardo Ciaccio
回答by Vitaly Gordon
I've made a simple embeddable script doing hot reload:
我制作了一个简单的可嵌入脚本进行热重载:
https://github.com/xpl/crx-hotreload
https://github.com/xpl/crx-hotreload
It watches for file changes in an extension's directory. When a change detected, it reloads the extension and refreshes the active tab (to re-trigger updated content scripts).
它监视扩展目录中的文件更改。当检测到更改时,它会重新加载扩展并刷新活动选项卡(以重新触发更新的内容脚本)。
- Works by checking timestamps of files
- Supports nested directories
- Automatically disables itself in the production configuration
- 通过检查文件的时间戳来工作
- 支持嵌套目录
- 在生产配置中自动禁用自身
回答by refaelio
Another solution would be to create custom livereload script (extension-reload.js):
另一种解决方案是创建自定义 livereload 脚本(extension-reload.js):
// Reload client for Chrome Apps & Extensions.
// The reload client has a compatibility with livereload.
// WARNING: only supports reload command.
var LIVERELOAD_HOST = 'localhost:';
var LIVERELOAD_PORT = 35729;
var connection = new WebSocket('ws://' + LIVERELOAD_HOST + LIVERELOAD_PORT + '/livereload');
connection.onerror = function (error) {
console.log('reload connection got error:', error);
};
connection.onmessage = function (e) {
if (e.data) {
var data = JSON.parse(e.data);
if (data && data.command === 'reload') {
chrome.runtime.reload();
}
}
};
This script connects to the livereload server using websockets. Then, it will issue a chrome.runtime.reload() call upon reload message from livereload. The next step would be to add this script to run as background script in your manifest.json, and voila!
此脚本使用 websockets 连接到 livereload 服务器。然后,它将根据来自 livereload 的重新加载消息发出 chrome.runtime.reload() 调用。下一步是将此脚本添加为在 manifest.json 中作为后台脚本运行,瞧!
Note: this is not my solution. I'm just posting it. I found it in the generated code of Chrome Extension generator(Great tool!). I'm posting this here because it might help.
注意:这不是我的解决方案。我只是发布它。我在Chrome 扩展生成器的生成代码中找到了它(很棒的工具!)。我在这里发布这个是因为它可能会有所帮助。
回答by GmonC
Chrome Extensions have a permission systemthat it wouldn't allow it (some people in SO had the same problem as you), so requesting them to "add this feature" is not going to work IMO. There's a mail from Chromium Extensions Google Groups with a proposed solution (theory)using chrome.extension.getViews(), but is not guaranteed to work either.
Chrome 扩展程序有一个不允许它的权限系统(SO中的某些人与您有同样的问题),因此要求他们“添加此功能”在 IMO 中是行不通的。有来自铬扩展谷歌群组邮件与建议的解决方案(理论)使用chrome.extension.getViews(),但不保证工作无论是。
If it was possible to add to the manifest.jsonsome Chrome internal pages like chrome://extensions/, it would be possible to create a plugin that would interact to the Reloadanchor, and, using an external program like XRefresh(a Firefox Plugin - there's a Chrome versionusing Ruby and WebSocket), you would achieve just what you need:
如果可以添加到manifest.json某些 Chrome 内部页面,例如chrome://extensions/,则可以创建一个与Reload锚点交互的插件,并且可以使用外部程序,例如XRefresh(Firefox 插件 - 有一个使用 Ruby 和 WebSocket的Chrome 版本),您将实现您所需要的:
XRefresh is a browser plugin which will refresh current web page due to file change in selected folders. This makes it possible to do live page editing with your favorite HTML/CSS editor.
XRefresh 是一个浏览器插件,由于选定文件夹中的文件更改,它将刷新当前网页。这使得使用您最喜欢的 HTML/CSS 编辑器进行实时页面编辑成为可能。
It's not possible to do it, but I think you can use this same concept in a different way.
这是不可能的,但我认为您可以以不同的方式使用相同的概念。
You could try to find third-party solutions instead that, after seeing modifications in a file (I don't know emacs neither Textmate, but in Emacs it would be possible to bind an app call within a "save file" action), just clicks in an specific coordinate of an specific application: in this case it's the Reloadanchor from your extension in development (you leave a Chrome windows opened just for this reload).
您可以尝试找到第三方解决方案,而不是在看到文件中的修改后(我不知道 emacs 和 Textmate,但在 Emacs 中可以在“保存文件”操作中绑定应用程序调用),只是单击特定应用程序的特定坐标:在这种情况下,它是Reload开发中的扩展程序的锚点(您只为这次重新加载而打开 Chrome 窗口)。
(Crazy as hell but it may work)
(疯狂到地狱,但它可能会奏效)
回答by Scott
Here's a function that you can use to watch files for changes, and reload if changes are detected. It works by polling them via AJAX, and reloading via window.location.reload(). I suppose you shouldn't use this in a distribution package.
这是一个函数,您可以使用它来监视文件的更改,并在检测到更改时重新加载。它的工作原理是通过 AJAX 轮询它们,并通过 window.location.reload() 重新加载。我想你不应该在分发包中使用它。
function reloadOnChange(url, checkIntervalMS) {
if (!window.__watchedFiles) {
window.__watchedFiles = {};
}
(function() {
var self = arguments.callee;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (__watchedFiles[url] &&
__watchedFiles[url] != xhr.responseText) {
window.location.reload();
} else {
__watchedFiles[url] = xhr.responseText
window.setTimeout(self, checkIntervalMS || 1000);
}
}
};
xhr.open("GET", url, true);
xhr.send();
})();
}
reloadOnChange(chrome.extension.getURL('/myscript.js'));
回答by Robin Drexler
Maybe I'm a little late to the party, but I've solved it for me by creating https://chrome.google.com/webstore/detail/chrome-unpacked-extension/fddfkmklefkhanofhlohnkemejcbamln
也许我参加聚会有点晚了,但我已经通过创建https://chrome.google.com/webstore/detail/chrome-unpacked-extension/fddfkmklefkhanofhlohnkemejcbamln为我解决了这个问题
It works by reloading chrome://extensionspage, whenever file.changeevents are incoming via websockets.
它通过重新加载chrome://extensions页面来工作,只要file.change事件通过 websockets 传入。
A Gulp-based example of how to emit file.changeevent upon file changes in an extension folder can be found here: https://github.com/robin-drexler/chrome-extension-auto-reload-watcher
file.change可以在此处找到有关如何在扩展文件夹中的文件更改时发出事件的基于 Gulp 的示例:https: //github.com/robin-drexler/chrome-extension-auto-reload-watcher
Why reloading the entire tab instead of just using the extensions management api to reload/re-enable extensions? Currently disabling and enabling extensions again causes any open inspection window (console log etc.) to close, which I found to be too annoying during active development.
为什么要重新加载整个选项卡而不是仅使用扩展管理 API 来重新加载/重新启用扩展?当前再次禁用和启用扩展会导致任何打开的检查窗口(控制台日志等)关闭,我发现在活动开发过程中这太烦人了。
回答by Eugene Kulabuhov
There's an automatic reload plugin if you're developing using webpack: https://github.com/rubenspgcavalcante/webpack-chrome-extension-reloader
如果您使用 webpack 进行开发,则有一个自动重新加载插件:https: //github.com/rubenspgcavalcante/webpack-chrome-extension-reloader
const ChromeExtensionReloader = require('webpack-chrome-extension-reloader');
plugins: [
new ChromeExtensionReloader()
]
Also comes with a CLI tool if you don't want to modify webpack.config.js:
如果你不想修改 webpack.config.js,还附带了一个 CLI 工具:
npx wcer
Note: an (empty) background script is required even if you don't need it because that's where it injects reload code.
注意:即使您不需要(空的)后台脚本,它也是必需的,因为它会注入重新加载代码。
回答by Johan Hoeksma
I am using a shortcut to reload. I don't want to reload all the time when I save a file
我正在使用快捷方式重新加载。我不想在保存文件时一直重新加载
So my approach is lightweight, and you can leave the reload function in
所以我的方法是轻量级的,你可以将重新加载功能保留在
manifest.json
清单文件
{
...
"background": {
"scripts": [
"src/bg/background.js"
],
"persistent": true
},
"commands": {
"Ctrl+M": {
"suggested_key": {
"default": "Ctrl+M",
"mac": "Command+M"
},
"description": "Ctrl+M."
}
},
...
}
src/bg/background.js
src/bg/background.js
chrome.commands.onCommand.addListener((shortcut) => {
console.log('lets reload');
console.log(shortcut);
if(shortcut.includes("+M")) {
chrome.runtime.reload();
}
})
Now press Ctrl + M in the chrome browser to reload
现在在 chrome 浏览器中按 Ctrl + M 重新加载


