简体   繁体   English

如何删除受外部脚本约束的事件侦听器

[英]How to remove event listeners bound by external script

I have 'black-box' type ASP framework, let's say I cannot modify it. 我有“黑匣子”类型的ASP框架,假设我无法对其进行修改。 But I can add HTML modules to it. 但是我可以向其中添加HTML模块。 I've made HTML module using AJAX for user logon and fetching data. 我已经使用AJAX制作了HTML模块,用于用户登录和获取数据。 The problem is I need to intercept submit event of the logon form. 问题是我需要拦截登录表单的Submit事件。 Then it has to call web service, return token and store it in a cookie before the page reloads. 然后,它必须调用Web服务,返回令牌并将其存储在Cookie中,然后页面才能重新加载。

First I need to stop the page from reloading. 首先,我需要停止重新加载页面。 So I need to unbind events which cause the reload. 因此,我需要取消绑定会导致重新加载的事件。 But how? 但是如何? I don't have access to code which bound the events. 我无权访问绑定事件的代码。 It's not mine. 不是我的。

I was able to attach my own event handlers to submit button, login and password fields. 我能够附加自己的事件处理程序来提交按钮,登录名和密码字段。 They do their job - they start the AJAX request which should perform my logon procedure. 他们完成了他们的工作-他们启动了AJAX请求,该请求应执行我的登录过程。 Well, at least they try, because almost always my AJAX call is killed before it can finish, the page reloads, and my module has no token it should have by then. 好吧,至少他们会尝试,因为几乎总是我的AJAX调用在完成之前就被杀死了,页面重新加载了,那时我的模块没有令牌了。 1 in about 20 calls - it succeeds, so it looks like possible to do. 大约20个电话中有1个-成功,因此似乎可以实现。

If there was a way to prevent page from reloading until the AJAX callback completes, it would probably be enough for it to work. 如果有一种方法可以防止页面在AJAX回调完成之前重新加载,则足以使其正常工作。

Is there absolutely no way of killing events which I din't bind in my code? 绝对没有办法杀死我在代码中未绑定的事件吗?

Well, I've found the way to achieve the goal without actually unbinding any events. 好吧,我已经找到了实现目标的方法,而无需实际解开任何事件。 I needed to replace the form action attribute with '#', the same with special submit link href ('#'), and... DONE! 我需要将表单操作属性替换为“#”,并使用特殊的提交链接href href(“#”)替换,然后...完成! After my AJAX call completes (or fails), it restores original hrefs and submits the naughty form. 我的AJAX调用完成(或失败)后,它将恢复原始的hrefs并提交顽皮的表单。

So the question I asked was wrong - my fault. 所以我问的问题是错的-我的错。 I needed to prevent a form from being submited and this is way easier than removing alien events! 我需要阻止提交表单,这比删除外来事件要容易得多!

TL;DR - kill hrefs first, then restore them :) TL; DR-首先杀死hrefs,然后恢复它们:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM