gpt4 book ai didi

google-chrome-extension - 如何自动重启 Chrome 扩展?

转载 作者:行者123 更新时间:2023-12-01 11:49:14 66 4
gpt4 key购买 nike

我有一个我构建的 chrome 扩展会泄漏内存。我正在努力修复内存泄漏,但与此同时,一些 friend 已经在使用它。

作为临时措施,我想包含一个补丁,它会定期自动重新启动扩展。

如何做到这一点?,即从扩展本身内重新启动 chrome 扩展。

谢谢,

最佳答案

你可以有两个扩展。并从另一个重新启动目标扩展。如果这适合您继续阅读。

内容.js

window.addEventListener('load', function (e) {
// create a button and add it to the page
var btn = document.createElement('button');
btn.innerHTML = 'Restart child extension';
btn.addEventListener('click', function (e) {
// on button click send message to the background script
chrome.extension.sendMessage({restart: true}, function (res) {
console.log(res);
});
}, false);

var body = document.querySelector('body');
body.appendChild(btn);
}, false);

背景.js
// first get your target (child) extension by it's name
var child = null;
chrome.management.getAll(function (info) {
for (var i=0; i < info.length; i++) {
if (info[i].name == 'Test child extension') {
child = info[i];
break;
}
}
});

function disable (cb) {
chrome.management.setEnabled(child.id, false, cb);
}
function enable (cb) {
chrome.management.setEnabled(child.id, true, cb);
}
function afterEnable () {
// notify the content script
resRestart({restarted: true});
}

var resRestart = null;
chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
// if we receive request with restart variable, save a reference to the
// sendResponse function and disable the child extension
switch (true) {
case request.restart: resRestart = sendResponse; disable(); break;
}
return true;
});
chrome.management.onDisabled.addListener(function (extension) {
// this one is fired when extension is restarted
// check if this is our child extension and re-enable it
if (extension.name == 'Test child extension') {
enable(afterEnable);
}
});

manifest.json(父)
{
"manifest_version": 2,
"name" : "Test parent extension",
"version" : "1.0",
"description" : "Whatever",

"background" : {
"scripts": [
"background.js"
]
},

"content_scripts": [
{
"matches": [
"*://localhost/*"
],
"js": [
"content.js"
],
"run_at": "document_end",
"all_frames": true
}
],

"permissions": [
"tabs",
"management",
"*://localhost/*"
]
}

manifest.json(子)
{
"manifest_version": 2,
"name" : "Test child extension",
"version" : "1.0",
"description" : "Whatever",

"content_scripts": [
{
"matches": [
"*://localhost/*"
],
"css": [
"style.css"
],
"run_at": "document_end",
"all_frames": true
}
]
}

目录结构
.
├── background.js
├── child
│   ├── manifest.json
│   └── style.css
├── content.js
└── manifest.json

立即开通 about:extensionshttp://localhost在分屏中。点击按钮,看看子扩展每次是如何刷新的。您也可以查看控制台。甚至尝试从 about:extensions 中禁用子扩展- 只要父扩展正在运行,就不可能。

关于google-chrome-extension - 如何自动重启 Chrome 扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13104360/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com