我不想将扩展程序的状态存储在单个chrome.storage
中,而是将每个选项卡存储在其中,该扩展程序是在任何页面上叠加一个网格系统,并且要在每个选项卡中存储最新更新,这里是一些代码:
popup.js
(function(){
let gridToggleBtn = document.querySelector('#grid-toggle-btn');
let widthInput = document.querySelector('#widthInput');
let opacityRange = document.querySelector('#opacityRange');
let colorPicker = document.querySelector('#colorPicker');
let state = false;
let chromeInject = function( key, file ) {
chrome.tabs[key]({
file
});
}
let chromeSync = function(key, value, rebuild) {
chrome.storage.sync.set({
[key]: value ? value : null,
rebuild: state
});
}
let chromeSyncCB = function(key) {
return function() {
chromeSync(key, this.value, true);
chromeInject('executeScript', 'inject.js');
}
}
let toggleCB = function(e){
state = !state;
if( state ) {
e.currentTarget.className += ' is-on';
} else {
e.currentTarget.className = 'grid-toggle-btn';
}
chrome.storage.sync.set( {
width: widthInput.value ? Number(widthInput.value) : null,
opacity: opacityRange.value ? opacityRange.value : null,
color: colorPicker.value ? colorPicker.value : null,
rebuild: state,
state
} );
chromeInject('executeScript', 'inject.js');
}
gridToggleBtn.onclick = toggleCB;
gridToggleBtn.addEventListener('mousedown', chromeInject.bind(null, 'insertCSS', 'inject.css'), { once : true });
widthInput.oninput = chromeSyncCB('width');
opacityRange.oninput = chromeSyncCB('opacity');
colorPicker.oninput = chromeSyncCB('color');
})();
inject.js
文件被注入
var getFromClient = () =>
new Promise( resolve =>
chrome.storage.sync.get( ['width', 'rebuild', 'state', 'opacity', 'color'], data => resolve( data ) ) );
var getFromClientCB = ( { width, rebuild, state, opacity, color } ) => {
const minWidth = 320;
const maxWidth = window.innerWidth;
const wrapWidth = ( width < minWidth || width > maxWidth ) ? maxWidth : width,
base = 12,
wrap = document.createElement('div');
wrap.id = "gridy-wrap";
wrap.className = width ? "gridy-wrap is-container" : "gridy-wrap";
wrap.style.width = wrapWidth + 'px';
wrap.style.opacity = opacity ? opacity : 1;
for (var i = 0; i < base; i++) {
const col = document.createElement('div');
col.className = `gridy-cols gridy-cols-${(i + 1)}`;
col.style.backgroundColor = color;
wrap.appendChild(col);
}
const wrapAlready = document.getElementById(wrap.id);
if( rebuild )
{
if( wrapAlready ) document.body.removeChild(wrapAlready);
document.body.appendChild(wrap);
} else if( !state ) {
if( wrapAlready ) {
document.body.removeChild(wrapAlready);
}
}
}
getFromClient().then( getFromClientCB )