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?
Using
@grant
enables the sandbox, which can sometimes result in difficulties when trying to interact with complicated page objects on Greasemonkey.If you do not want to enable the sandbox with
@grant
, another option is to have the userscript create an iframe to the other domain, and then post a message to it. On the other domain, in the iframe, listen for messages. When a message is received, useBroadcastChannel
to send the message to every other tab on that other domain, and your other tabs with the userscript running can have the same BroadcastChannel open and listen for messages.For example, to create a userscript on
stackoverflow.com
that can send a message to a userscript running in a different tab onexample.com
:This results in:
If you want two-way communication, not just one-way communication, have both parent pages create a child iframe to a single target domain (say, to
example.com
). To communicate to other tabs, post a message to the child iframe. Have the child iframe listen for messages, and when seen, post a BroadcastChannel message to communicate with all other iframes. When an iframe receives a BroadcastChannel message, relay it to the parent window withpostMessage
.In the above code, a tab on Stack Overflow sends a message to a tab on Stack Exchange. Result screenshot: