Có một cách để cho phép một phần mở rộng nặng nội dung kịch bản để tiếp tục hoạt động sau khi nâng cấp, và làm cho nó hoạt động ngay lập tức sau khi cài đặt.
Install
Phương pháp cài đặt chỉ đơn giản là lặp qua tất cả các tab trong tất cả các cửa sổ, và tiêm một số kịch bản lập trình vào tab với các URL khớp.
Rõ ràng, bạn phải làm điều đó trong một kịch bản background page hoặc event page khai báo trong manifest.json:
"background": {
"scripts": ["background.js"]
},
background.js:
// Add a `manifest` property to the `chrome` object.
chrome.manifest = chrome.app.getDetails();
var injectIntoTab = function (tab) {
// You could iterate through the content scripts here
var scripts = chrome.manifest.content_scripts[0].js;
var i = 0, s = scripts.length;
for(; i < s; i++) {
chrome.tabs.executeScript(tab.id, {
file: scripts[i]
});
}
}
// Get all windows
chrome.windows.getAll({
populate: true
}, function (windows) {
var i = 0, w = windows.length, currentWindow;
for(; i < w; i++) {
currentWindow = windows[i];
var j = 0, t = currentWindow.tabs.length, currentTab;
for(; j < t; j++) {
currentTab = currentWindow.tabs[j];
// Skip chrome:// and https:// pages
if(! currentTab.url.match(/(chrome|https):\/\//gi)) {
injectIntoTab(currentTab);
}
}
}
});
Upgrade
phương pháp
Việc nâng cấp dựa trên thực tế là các tập lệnh nội dung được tiêm trái sau khi một phần mở rộng bị tắt, gỡ cài đặt hoặc nâng cấp.
Khi kết nối cổng được thực hiện, bộ xử lý onDisconnect được thêm vào. Điều này chờ một giây sau sự kiện ngắt kết nối, sau đó thử kết nối lại. Nếu nó không thành công, một onDisconnect khác sẽ được kích hoạt để quá trình này xảy ra lần nữa, cho đến khi kết nối được thực hiện. Nó không hoàn hảo, nhưng nó hoạt động.
Các kịch bản nội dung:
var port;
// Attempt to reconnect
var reconnectToExtension = function() {
// Reset port
port = null;
// Attempt to reconnect after 1 second
setTimeout(connectToExtension, 1000 * 1);
};
// Attempt to connect
var connectToExtension = function() {
// Make the connection
port = chrome.runtime.connect({name: "my-port"});
// When extension is upgraded or disabled and renabled, the content scripts
// will still be injected, so we have to reconnect them.
// We listen for an onDisconnect event, and then wait for a second before
// trying to connect again. Becuase chrome.runtime.connect fires an onDisconnect
// event if it does not connect, an unsuccessful connection should trigger
// another attempt, 1 second later.
port.onDisconnect.addListener(reconnectToExtension);
};
// Connect for the first time
connectToExtension();
Hình như Safari 7 (ít nhất) không còn tự động làm mới trang khi một phần mở rộng được cài đặt – baseten