开发者

Get 2 userscripts to interact with each other?

开发者 https://www.devze.com 2023-03-27 15:13 出处:网络
I have two scripts. I put them in the same namespace (the @namespace field). I\'d like them to interactive with another.

I have two scripts. I put them in the same namespace (the @namespace field).

I'd like them to interactive with another.

Specifically I want script A to set RunByDefault to 123. Have script B check if RunByDefault==123 or not and then have script A using a timeout or anything to call开发者_StackOverflow a function in script B.

How do I do this? I'd hate to merge the scripts.


The scripts cannot directly interact with each other and // @namespace is just to resolve script name conflicts. (That is, you can have 2 different scripts named "Link Remover", only if they have different namespaces.)

Separate scripts can swap information using:

  • Cookies -- works same-domain only
  • localStorage -- works same-domain only
  • Sending and receiving values via AJAX to a server that you control -- works cross-domain.

That's it.

Different running instances, of the same script, can swap information using GM_setValue() and GM_getValue(). This technique has the advantage of being cross-domain, easy, and invisible to the target web page(s).

See this working example of cross-tab communication in Tampermonkey.


On Chrome, and only Chrome, you might be able to use the non-standard FileSystem API to store data on a local file. But this would probably require the user to click for every transaction -- if it worked at all.

Another option is to write an extension (add-on) to act as a helper and do the file IO. You would interact with it via postMessage, usually.

In practice, I've never encountered a situation were it wasn't easier and cleaner to just merge any scripts that really need to share data.


Also, scripts cannot share code, but they can inject JS into the target page and both access that.

Finally, AFAICT, scripts always run sequentially, not in parallel. But you can control the execution order from the Manage User Scripts panel

0

精彩评论

暂无评论...
验证码 换一张
取 消