lulu0601 发表于 2025-8-16 10:49:37

求助:在A网页上运行的脚本判断B网页是否打开

在电脑浏览器上已经打开了A网页,然后脚本自动点A网页上的链接,在新窗口打开了B网页,过2分钟后自动关闭B网页。那么在A网页上运行的JS脚本如何判断B网页的状态,A网页上JS脚本如何判断目前B网页是否已打开了或还是关闭了?我是JS初学者,水平有限,请各位大神们给个方案,帮忙给个完整的代码段,谢谢了!!!

wilsons 发表于 2025-8-16 10:49:38

本帖最后由 wilsons 于 2025-8-25 15:48 编辑

> 本帖最后由 wilsons 于 2025-8-18 04:48 编辑

> 本帖最后由 wilsons 于 2025-8-18 04:24 编辑

> (forum.php?mod=redirect&goto=findpost&pid=99664&ptid=9358)
> > 可以帮忙给外完整的代码块吗?我初学者,代码我实在是写不出来。

测试页面 [https://wilson.lovestoblog.com/demo/A.html](https://wilson.lovestoblog.com/demo/A.html)

油猴demo脚本

```js
// ==UserScript==
// @name         GM_addValueChangeListener demo
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @descriptionGM_addValueChangeListener demo. see https://bbs.tampermonkey.net.cn/thread-9358-1-1.html
// @author       Wilsons
// @match      https://wilson.lovestoblog.com/demo/A.html
// @match      https://wilson.lovestoblog.com/demo/B.html
// @match      https://www.baidu.com/*
// @grant      GM_addValueChangeListener
// @grant      GM_setValue
// ==/UserScript==

(function() {
    'use strict';

    const closedPage = '__closed_page';
    if(location.href.includes('demo/A.html')) {
      GM_setValue(closedPage, '');
      GM_addValueChangeListener(closedPage, (name, old_value, new_value, remote)=>{
            GM_setValue(closedPage, '');
            if(new_value === 'B.html') alert('B closed');
            else if(new_value === 'baidu.com') alert('baidu.com closed');
      });
    }
    if(location.href.includes('demo/B.html')) {
      setTimeout(()=>{
            GM_setValue(closedPage, 'B.html');
            setTimeout(()=>window.close(), 50); // 延迟更保险
      }, 5000);
    }

    if(location.href.includes('baidu.com')) {
      setTimeout(()=>{
            GM_setValue(closedPage, 'baidu.com');
            setTimeout(()=>window.close(), 50); // 延迟更保险
      }, 5000);
    }
})();
```

操作步骤:

第一步,写油猴脚本

第二步,打开测试页面测试

注意: 如果scriptcat测试有问题,可以用tampermonkey测试,我测试下来,发现scriptcat有bug,偶有监听不到的情况。

王一之 发表于 2025-8-16 16:59:50

可以使用 GM_get/saveTab/GM_getTabs 定时检查B窗口存不存在,另外如果是通过window.open打开的B窗口,会有一个b窗口的window返回,也可以拿这个去判断检测

https://docs.scriptcat.org/docs/dev/api/#gm_getsavetabgm_gettabs

潘钜森 发表于 2025-8-16 17:41:26

**something just like this ???**

```
// ==UserScript==
// @name         New Userscript
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @descriptiontry to take over the world!
// @author       You
// @match      *
// @run-at       document-end
// @grant      unsafeWindow
// @grant      GM_getValue
// @grant      GM_setValue
// ==/UserScript==

function getRandomSecond(min = 1, max = 1) {
    return Math.floor(Math.random() * (max + 1 - min) + min) * 1000
}

function getRandomHanzi() {
    const codePoint = Math.floor(Math.random() * (0x9FFF - 0x4E00 + 1)) + 0x4E00
    return String.fromCodePoint(codePoint)
}

function generateRandomHanzi(min = 1, max = 18) {
    const length = Math.floor(Math.random() * (max - min + 1)) + min
    let result = ""
    for (let i = 0; i < length; i++) {
      result += getRandomHanzi()
    }
    return result
}

function openUrl() {
    setTimeout(() => {
      window.open(`https://bing.com/search?q=${generateRandomHanzi()}&form=QBLH`, "_self")
    }, getRandomSecond(6, 9))
}

const DATA_LINK = ".bing.com/search?q="
if (location.href.includes(DATA_LINK)) {
    const links = document.querySelectorAll(`li h2 a:not()`)
    if (links.length > 0) {
      GM_setValue("host", links.host)
      GM_setValue("status", 0)
      setTimeout(() => {
            links.click()
            console.log("Click Done!")
      }, 1e3)
      const isOpened = setInterval(() => {
            if (GM_getValue("status", 0) == 1) {
                console.log("Open Done!")
                GM_setValue("status", 0)
                clearInterval(isOpened)
            }
      }, 1e3)
      const isClosed = setInterval(() => {
            if (GM_getValue("status", 0) == 2) {
                console.log("Close Done!")
                clearInterval(isClosed)
                openUrl()
            }
      }, 1e3)
      setTimeout(() => {
            if (GM_getValue("status", 0) == 0) {
                console.log("Timeout!")
                clearInterval(isOpened)
                clearInterval(isClosed)
                openUrl()
            }
      }, 3e4)
    } else {
      console.log("Can not find links!")
      openUrl()
    }
}

const DATA_HOST = GM_getValue("host", null)
if (DATA_HOST && location.href.includes(DATA_HOST)) {
    GM_setValue("status", 1)
    setTimeout(() => {
      window.close()
      GM_setValue("host", null)
      GM_setValue("status", 2)
    }, getRandomSecond(3, 6))
}
```

wilsons 发表于 2025-8-16 18:18:15

如果逻辑简单,最简单的方式是用GM_addValueChangeListener,我经常这么用。

A监听,B关闭前用GM_setValue修改数据即可。

然后A中的回调函数就能被回调,从而感知到B的关闭。

lulu0601 发表于 2025-8-17 21:17:02

wilsons 发表于 2025-8-16 18:18
如果逻辑简单,最简单的方式是用GM_addValueChangeListener,我经常这么用。

A监听,B关闭前用GM_setValue ...

可以帮忙给外完整的代码块吗?我初学者,代码我实在是写不出来。

lulu0601 发表于 2025-8-18 21:45:38

wilsons 发表于 2025-8-18 04:22
> 本帖最后由 wilsons 于 2025-8-18 04:24 编辑

> (forum.php?mod ...

用tampermonkey测试可以了,这可帮了我大忙了,非常感谢!

wilsons 发表于 2025-8-18 22:14:56

本帖最后由 wilsons 于 2025-8-18 22:16 编辑

> (forum.php?mod=redirect&goto=findpost&pid=99716&ptid=9358)
> > 用tampermonkey测试可以了,这可帮了我大忙了,非常感谢!

不客气哈

@王一之

这个是bug吗?脚本猫经常监听不到。

王一之 发表于 2025-8-18 23:34:40

wilsons 发表于 2025-8-18 22:14
> (forum.php?mod=redirect&goto=findpost&pid=99716&ptid=9358)
>...

啊?不应该,哥哥可以去提一个issue反馈一下,我有空再排查 https://github.com/scriptscat/scriptcat/issues/new?template=bug_report.yaml&scriptcat-version=1.1.0-beta

wilsons 发表于 2025-8-19 00:34:44

王一之 发表于 2025-8-18 23:34
啊?不应该,哥哥可以去提一个issue反馈一下,我有空再排查 https://github.com/scriptscat/scriptcat/is ...
OK,已提

https://github.com/scriptscat/scriptcat/issues/641
页: [1]
查看完整版本: 求助:在A网页上运行的脚本判断B网页是否打开