You can use GM_getValue
, GM_setValue
& GM_addValueChangeListener
to achieve cross-tab user script communication.
Add the following lines in your user script header.
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addValueChangeListener
The following lines of rough code will simplify the cross-tab user script communication.
function GM_onMessage(label, callback) {
GM_addValueChangeListener(label, function() {
callback.apply(undefined, arguments[2]);
});
}
function GM_sendMessage(label) {
GM_setValue(label, Array.from(arguments).slice(1));
}
So all you'll need to do is the following to send and receive messages.
GM_onMessage('_.unique.name.greetings', function(src, message) {
console.log('[onMessage]', src, '=>', message);
});
GM_sendMessage('_.unique.name.greetings', 'hello', window.location.href);
NOTE Sending messages may not trigger your callback if the message sent is the same as before. This is due to GM_addValueChangeListener
not firing because the value has not changed, i.e. same value as before even though GM_setValue
is called.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…