我正在尝试使用 GM_setValue
将 DOM 元素选择到 Tampermonkey 变量中,以便稍后注入(inject)到不同的页面上。
我创建了一个示例,可以在普通 jQuery 中使用 .clone()
执行此操作,但是当我将其设置为 Tampermonkey 中的值时,它会更改已保存变量的值。
这是一个用于测试脚本的 HTML 页面:
<!DOCTYPE html>
<html><head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link rel="stylesheet" href="style.css"/>
<style>
div {
border: solid 1px black;
margin: 5px;
padding: 5px;
}
</style>
</head>
<body>
<!-- these buttons controlled by grease monkey-->
<div>
GreaseMonkey <button id="copy"> save</button>
<button id="paste"> paste </button>
</div>
<div>
Local <button id="copyLocal"> save</button>
<button id="pasteLocal"> paste </button>
</div>
<div id="bar"> hello world </div>
<script>
var ele;
$("#copyLocal").click(function() {
console.log("copy");
ele = $("#bar").clone();
console.log(ele);
});
$("#pasteLocal").click(function(){
console.log("paste");
console.log(ele);
$("body").append(ele);
});
</script>
</body>
</html>
这是相应的 Tampermonkey/Greasemonkey 脚本:
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js
// @match file:///C:/david/sandbox/jquery/index.html
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
(function() {
'use strict';
$(document).ready(function() {
$("#copy").click(function() {
console.log("copy");
var ele = $("#bar").clone();
console.log(ele);
GM_setValue("ele", ele);
});
$("#paste").click(function(){
console.log("paste");
var ele = GM_getValue("ele");
console.log(ele);
$("body").append(ele);
});
console.log("ready");
});
})();
这是控制台输出:
正如您所看到的 - Tampermonkey(我也用 Greasemonkey 尝试过)似乎正在从 jQuery 对象中剥离 jQuery。
最佳答案
GM_setValue()
only works on: strings, (some) integers and booleans .
在您的代码中,ele
是一个对象。
现在,对于简单对象,您可以通过首先对它们进行 JSON 编码来对其进行 GM_setValue 操作。但是您的对象是一个复杂的 jQuery 对象,并且这些对象不能进行 JSON 编码。 (曾几何时 the attempt would throw a JS error 。如今,JSON.stringify
将忽略所有有问题的属性,让您得不到最需要的内容。)
问题表明您显然只是克隆 HTML。如果这是真的,那么您不需要尝试存储 jQuery 对象。只需存储 HTML。
类似这样的事情:
// ==UserScript==
// @name New Userscript
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js
// @match file:///C:/david/sandbox/jquery/index.html
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
$("#copy").click (function () {
console.log ("copy");
var ele = $("#bar").html ();
console.log (ele);
GM_setValue ("ele", ele);
} );
$("#paste").click (function () {
console.log ("paste");
var ele = GM_getValue ("ele");
console.log (ele);
$("body").append (ele);
} );
console.log ("ready");
PS:我省略的包装垃圾是 GM/TM 脚本中几乎不需要的东西。
关于jquery - 当我使用 GM_setValue 时,Greasemonkey/Tampermonkey 对我的 jQuery 对象做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929417/