tampermonkey 跨域名共享数据的方法

发布时间: 2020-06-21 17:09:52 作者: 大象笔记

在使用 tampermonkey 挂学时时,遇到一个问题。课程列表页与视频页所属不同二级域名,导致这两个页面对应的 tm 脚本无法共享 cookie。

在查解决方案时,查到 tm 自带的 gm set get value 函数,可以跨域共享数据,但前提是读写都在一个 tm 脚本中。

参考:

http://greasemonkey.win-start.de/advanced/gm_getvalue.html

Data stored with GM_setValue and retrieved with GM_getValue are similar to browser cookies, but there are important differences. Both are stored on the local machine, but while cookies are domain-specific and can only be accessed from their originating domain, Greasemonkey configuration values are script-specific and can only be accessed by the user script that created them (regardless of the URL that the user script is currently running on). And unlike cookies, user script data are never transmitted to remote servers.

也就是说只要是同一个 tampermonkey 脚本 GM_setValue 设置的数据,在不同域名下也可以读取到。而且不会上传到服务器。那就非常方便地解决了跨域不能共享 cookie 的问题。

所以有两套改造方案。

方案一

把所有逻辑都写在一个 tm 脚本中,然后通过 set get value 函数共享数据。

方案二

继续使用原分离脚本的方案,但是在列表脚本中 match 视频页的处理。逻辑是:

这样就解决了。而且这样改动最小,所以暂时使用该方案。

总结

但是,从维护性上讲,还是方案一,更容易维护。分发给别人也方便。

我是一名山东烟台的开发者,联系作者