GM_addValueChangeListener 函数的使用 详解 编写高级扩展浏览器脚本

在TM的文档中有这样一个API

GM_addValueChangeListener

GM_addValueChangeListener(name, function(name, old_value, new_value, remote) {})

Adds a change listener to the storage and returns the listener ID.
'name' is the name of the observed variable.
The 'remote' argument of the callback function shows whether this value was modified from the instance of another tab (true) or within this script instance (false).
Therefore this functionality can be used by scripts of different browser tabs to communicate with each other.

这个API的作用就是可以对存储在GM中的变量进行监听,当值变化时,可以触发一个函数,

name是要监听的变量名称, 字符串类型, name指向的变量必须是基本数据类型,如果是js中的引用类型object是无法触发监听函数的

监听函数,第一个参数是变量名称, 第二个是旧值,第三个是新值, 第四个是表示,值的变化是在当前浏览器窗口还是其他脚本触发的, 其他窗口为true 其他脚本触发的为false

具体用法需要搭配GM_setValue 函数,对变量进行赋值

具体用法如下

// ==UserScript==
// @name         allOpen
// @namespace    https://fizzz.blog.csdn.net/
// @version      0.1
// @description  try to take over the world!
// @author       Fizz
// @grant        GM_setValue
// @grant        GM_addValueChangeListener


// ==/UserScript==

(function () {
  'use strict';
  GM_setValue('globalStatu', 'initial') // open close
  GM_addValueChangeListener('globalStatu', function(name, old_value, new_value, remote) {
    console.log(name, old_value, new_value, remote)
    window.location.href="https://fizzz.blog.csdn.net/";
    window.close();
  })

  GM_setValue('globalStatu', 'close')

})

使用GM_addValueChangeListener 可以很简单地编写跨浏览器窗口的脚本. 就是如此简单 强大

发布了177 篇原创文章 · 获赞 875 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/github_35631540/article/details/103489068