gpt4 book ai didi

javascript - 单击链接时,Tampermonkey 对 href 的更改会恢复

转载 作者:行者123 更新时间:2023-11-30 20:10:29 24 4
gpt4 key购买 nike

我想使用 Tampermonkey 更改 ID 为“apple”的元素中的 href

我的代码有效,它将 href 更改为 www.google.com。但是,当我单击该链接时,它会将我带到旧网站 www.somewebsite.com

我不知道为什么会这样。 Tampermonkey 会不会延迟运行我的脚本?就好像浏览器已经缓存了旧的 href,所以虽然 jQuery 脚本改变了 href,但是当点击按钮时它会将你带到旧的网站?

<div>
<a id="apple" href="www.somewebsite.com">click to visit my website<a/>
</div>

var GMnode,GMelID;
GMelID="nav-questions";
GMnode=document.getElementById("apple");
if((GMnode!==null)&&(GMnode.hasAttribute("href"))){
GMnode.setAttribute("href","http://www.google.com/");
}

// ==UserScript==
// @name Apple
// @namespace http://tampermonkey.net/
// @version 0.1
// @description testing!
// @author You
// @match *://*/*
// @run-at document-end
// @require https://code.jquery.com/jquery-3.3.1.min.js
// @grant none
// ==/UserScript==

最佳答案

问题需要 MCVE 或实际页面的链接。

我们无法判断发生了什么,因为尚未提供所需的示例,但页面使用了多种技术来屏蔽或重写链接。他们这样做是出于邪恶的目的——或者是为了广告(但我重复一遍)——目的。

因此,您的脚本失败要么是因为它触发得太早,要么是因为页面在您单击链接时正在重写链接。

  1. 当您将鼠标悬停在链接上时,它会显示 www.google.com 还是 www.somewebsite.com
  2. 当您在没有启用 javascript 的情况下加载该页面时会发生什么?

无论如何,有时有用的技术是忽略链接并创建自己的链接,如下所示:

// ==UserScript==
// @name Apple
// @match *://YOUR_SERVER.COM/YOUR_PATH/*
// @run-at document-end
// @require https://code.jquery.com/jquery-3.3.1.min.js
// @grant GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.
/* global $ */
/* eslint-disable no-multi-spaces */

var targId = "apple";
var badLink = $("#" + targId);
var goodLink = badLink.clone ().attr ("id", `TM${targId}`).attr ("href", "https://www.google.com/");

badLink.hide ().after (goodLink);

但是有些页面更难以编写脚本。 提供您所看到的工作示例。

关于javascript - 单击链接时,Tampermonkey 对 href 的更改会恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52466029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com