我问了一个问题,并在这里得到了答案:如何从Greasemonkey调用这个YouTube函数?
该代码可以工作,并在页面上添加一个按钮,该按钮捕获视频时间。
但是,关键部分必须在目标页作用域中运行——Greasemonkey的GM_
函数不可用。
我想用GM_setValue()
来记录视频时间。我如何从我的按钮的click
处理程序调用GM_setValue()
?
下面是完整脚本的相关部分(右键单击保存):
... ...
//-- Only run in the top page, not the various iframes.
if (window.top === window.self) {
var timeBtn = document.createElement ('a');
timeBtn.id = "gmTimeBtn";
timeBtn.textContent = "Time";
//-- Button is styled using CSS, in GM_addStyle, below.
document.body.appendChild (timeBtn);
addJS_Node (null, null, activateTimeButton);
}
function activateTimeButton () {
var timeBtn = document.getElementById ("gmTimeBtn");
if (timeBtn) {
timeBtn.addEventListener ('click',
function () {
var ytplayer = document.getElementById ("movie_player");
//-- IMPORTANT: GM_functions will not work here.
console.log ("getCurrentTime(): ", ytplayer.getCurrentTime() );
alert (ytplayer.getCurrentTime() );
},
false
);
}
else {
alert ("Time button not found!");
}
}
... ...
谢谢:-)
要从必须在页面范围内运行的代码(例如您的timeBtn
单击处理程序)中使用Greasemonkey的GM_
函数,请执行以下操作:
- 让页作用域代码使用
postMessage
以字符串格式发送数据 - 让Greasemonkey脚本监听适当的消息,并使用消息数据调用所需的
GM_
函数。 使用JSON安全地将数据打包成字符串。
将window.postMessage ()
和window.addEventListener ("message"...
添加到您的代码中,它变成:
... ...
//-- Only run in the top page, not the various iframes.
if (window.top === window.self) {
var timeBtn = document.createElement ('a');
timeBtn.id = "gmTimeBtn";
timeBtn.textContent = "Time";
//-- Button is styled using CSS, in GM_addStyle, below.
document.body.appendChild (timeBtn);
addJS_Node (null, null, activateTimeButton);
window.addEventListener ("message", receiveTimeMessage, false);
}
function activateTimeButton () {
var timeBtn = document.getElementById ("gmTimeBtn");
if (timeBtn) {
timeBtn.addEventListener ('click',
function () {
var ytplayer = document.getElementById ("movie_player");
/*-- GM_functions will not work here, so send the data
back to the GM script scope.
*/
//-- Tag the message, we may not be the only ones sending.
var messageTxt = JSON.stringify (
{currentVidTime: ytplayer.getCurrentTime ()}
);
window.postMessage (messageTxt, "*");
},
false
);
}
else {
alert ("Time button not found!");
}
}
function receiveTimeMessage (event) {
var messageJSON;
try {
messageJSON = JSON.parse (event.data);
}
catch (zError) {
// Do nothing
}
if ( ! messageJSON || ! messageJSON.currentVidTime)
return; //-- Message is not for us.
/*--- We have a time value, set it with GM_setValue ()
But, WARNING: First make sure that the stored value is
a safe string. GM_setValue() crashes on just about anything else.
*/
var safeValue = JSON.stringify (messageJSON.currentVidTime);
GM_setValue ("videoMarkedTime", safeValue);
console.log ("Video time recorded with GM_setValue ().");
}
... ...
您可以打开about:config
并搜索videoMarkedTime
来查看存储的值。