在 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 中一样使用它?
最佳答案
GM_getResourceURL()
目前在 Greasemonkey 和 Tampermonkey 中的行为非常不同。
- 在油猴中,a special protected URL is provided for the file .
- Tampermonkey仍然遵循base64 encoding the file的旧方式并提供服务。
(请注意,Greasemonkey 在 GM 版本 1.0 之前的行为方式相同。)
我想说,这是 Tampermonkey 的一个 bug,因为直接从磁盘提供资源比读取资源、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 。)
关于base64 - GM_getResourceURL 在 Firefox 中不适用于二进制对象,但在 Tampermonkey 中适用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33338649/