gpt4 book ai didi

javascript - 劫持 DOM 操作

转载 作者:行者123 更新时间:2023-11-30 05:31:40 28 4
gpt4 key购买 nike

我有一个问题。我试图在音频元素发生变化时立即获取它的来源,而不是让它连接到服务器。让我详细说明一下:服务器只允许一个请求(随机生成的内容 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。反正有字面上劫持属性更改吗?

最佳答案

你是对的,MutationObserver 不能做你需要的。这些工作的方式是,浏览器在脚本运行时收集突变记录,然后在脚本产生时立即将记录传递给观察者。这几乎是异步的。这就是变异 观察者 比同步调度的变异 事件 表现更好的原因。当观察者运行时,audio 元素将收到 URL 并开始加载它。


假设您正在谈论的这个 onclick 处理程序设置了元素的 .src 属性,您需要为此定义一个自定义 setter ,以便您可以在 audio 元素的实现处理它之前拦截该值。

您可以在 JavaScript 中定义这样的 setter: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 中,这将使之后无法调用原始 setter ,但听起来您并不担心这一点。


另一种修改元素属性的方法是使用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);
};

当你给一个方法打补丁时,你可以保存原来的方法函数,这很有用。

关于javascript - 劫持 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26535963/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com