我有个问题。我试图获得一个音频元素的来源,一旦它改变,而不让它连接到服务器。让我详细说明:服务器只允许一个请求(为内容随机生成的url ),这是我正在尝试获得的,显然我不希望使用新的源重新加载音频元素。我目前使用的是一个变异观察者,但是没有比onclick更快的速度(是的,为了不让任何人直接获取源代码,涉及到复杂的js )。
document.getElementsByTagName('audio')[0].setAttribute("autoplay", false);
//not sure if ^^ makes a difference
audioObserver = new MutationObserver(function (mutations) {
window.open(mutations[0].target.src);
//I only listen for one mutation and want to open the url in a new window
audioObserver.disconnect();
//don't listen in order to not cause infinite loop
document.getElementsByTagName('audio')[0].parentNode.removeChild(document.getElementsByTagName('audio')[0]);
//remove the element in order to avoid reloading
});
observerConfig = {
attributes: true,
childList: false,
characterData: false
};
audioObserver.observe(document.getElementsByTagName('audio')[0], observerConfig);我对任何实现(不一定是MutationObserver )都很满意。是否真的存在劫持属性更改的问题?
发布于 2014-10-24 21:33:33
你说得对,MutationObserver不能做你想做的事。根据这些工作方式,浏览器在脚本运行时收集突变记录,然后在脚本生成时立即将记录传递给观察者。这几乎是异步的。这使得变异观察者的性能要好于同步分派的变异事件。当观察者运行时,audio元素将接收到该URL并开始加载它。
假设您正在讨论的这个onclick处理程序设置了元素的.src属性,那么您需要为此定义一个自定义设置器,以便在audio元素的实现处理它之前拦截该值。
您可以在JavaScript:http://jsfiddle.net/omqdx8d1/中定义这样的设置器
var el = document.getElementsByTagName('audio')[0];
Object.defineProperty(el, 'src', {
set: function (newSrc) {
console.log('they set src to ' + newSrc);
}
});在Chrome,这将使它不可能打电话给原来的设置,但听起来你不担心这一点。
另一种修改元素属性的方法是使用setAttribute方法。如果您想拦截它,可以重新定义元素的setAttribute方法。
下面是另一个使用setAttribute的示例:http://jsfiddle.net/5mLysc9n/1/
var el = document.getElementsByTagName('audio')[0];
var origSetAttribute = el.setAttribute;
el.setAttribute = function (name, value) {
console.log('they set ' + name + ' to ' + value);
// origSetAttribute.call(el, name, value);
};当您猴子补丁一个方法,您可以保存原来的方法函数,这可能是有用的。
https://stackoverflow.com/questions/26535963
复制相似问题