【发布时间】:2020-01-15 16:07:15
【问题描述】:
我正在尝试使用 GM_setValue 将 DOM 元素选择到 Tampermonkey 变量中,以便稍后在不同页面上注入。
我创建了一个示例,我可以在普通 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 对象中剥离出来。
【问题讨论】:
标签: jquery greasemonkey tampermonkey