Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

javascript - TamperMonkey - message between scripts on different subdomains

I have two scripts. Each runs on a different subdomain of our company "Example.com".

Script #1 -- house.example.com
Script #2 -- bob.fred.example.com

Same domain, different subdomains.

When a particular element appears on house.example.com, I need to send a message over to the script running on bob.fred.example.com

Since Google extensions can exchange messages between extensions, there must be a way with TamperMonkey to exchange messages within the same extension, between scripts -- especially if they run on the same second-level domain.

Can anyone point me in the right direction? An example or two would be worth their weight in gold.


Update: Although Gothdo referenced Javascript communication between browser tabs/windows as containing an answer to this question, he failed to take into consideration the cross-origin policies involved. None of the answers in that referenced question provide a clear answer for cross-origin browser tab communications, which was the main point of this question. I have now researched and solved this problem, getting ideas from a number of SO and non-SO sources. If this question is re-opened, I will post my solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...