在Tampermonkey中,以下用于添加带有来自OGG资源的base64数据的音频元素的代码可以正常工作:
var m = GM_getResourceURL("music") || null;
$("html").append('<audio id="audio" autoplay loop src="data:audio/ogg;base64,' + m + '" />')
在Greasemonkey中,m
不是base64字符串,它是一些UUID,后跟资源名称。如何从资源中获取实际的base64数据并像在Tampermonkey中那样使用它?
答案 0 :(得分:2)
GM_getResourceURL()
目前在Greasemonkey和Tampermonkey中表现得非常不同。
我说这是Tampermonkey的一个小错误,因为它更有效地直接从磁盘上提供资源,而不是:读取它,base64编码它,然后让它浏览器必须对它进行base64解码才能使用它。
无论如何,这是一个完整的工作脚本,可以在Greasemonkey和Tampermonkey中运行:
// ==UserScript==
// @name _Using a binary resource
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @include http://stackoverflow.com/questions/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @resource musicFile https://mdn.mozillademos.org/files/2587/AudioTest%20%281%29.ogg
// @grant GM_getResourceURL
// ==/UserScript==
var musicResrc = GM_getResourceURL ("musicFile");
/*--- GM_getResourceURL() currently behaves very differently in Greasemonkey versus Tampermonkey.
In Greasemonkey, a special protected URL is provided to the file.
Tampermonkey still follows the old way of base64 encoding the file and serving that.
The GM URL looks like:
greasemonkey-script:402c80a8-c313-439c-9d7b-c9bdc52b7b02/musicFile
*/
if (typeof musicResrc === 'string' && musicResrc.slice(0, 12) === "greasemonkey") {
console.log ("Greasemonkey mode.");
}
else {
console.log ("Tampermonkey mode.");
musicResrc = 'data:audio/ogg;base64,' + musicResrc;
}
//console.log ("musicResrc: ", musicResrc);
$("body").prepend (
'<div><audio type="audio/ogg" src="' + musicResrc + '" autoplay="true" loop="true" controls="true"></audio></div>'
);
请注意,Firefox的某些(所有?我的?)安装不会以这种方式自动播放音频。 (和it's generally a very poor practice。)