Reputation: 2231
I want to delete an event handler form a form that contains an inline definition of onsubmit.
<form id="loginForm" onsubmit="return performTask(this);">
I have already try :
$("#loginForm").off("submit")
$("#loginForm").unbind("submit")
$("#loginForm").die("submit")
$("#loginForm").removeAttr("onsubmit")
$("#loginForm").removeProp("onsubmit")
$("#loginForm").attr("onsubmit", "")
$("#loginForm").prop("onsubmit, "")
$("#loginForm")[0].onsubmit = null
$("#loginForm")[0].onsubmit = undefined
$("#loginForm")[0].onSubmit = null
$("#loginForm")[0].onSubmit = undefined
And nothing works !
I add my own event listener usin jquery method on() but it is never called. It apear that the old event listener is executed before mine... It does the same thing with onClick event on button.
I have to explicit that I'm in a chrome extension and more precisely in a Content Script injected in a page.
So the question is, is there any way to purge event handlers ? Or much better is there any way to add an event listener that will be call before the inline handler ?
EDIT : After lot of ugly code, I have find a way to do what I want... I do a copy of the form, delete the inline envent handler, replace in the dom the old form by mine and then create my event handler. It's ugly but it works ... If anyone can explain why I can't do this other way ...
Upvotes: 3
Views: 1258
Reputation: 77541
This is an isolated world problem. Chrome extensions run is a separate context from the page; while access to the DOM is shared, inline event listeners are isolated.
Quote from the documentation, emphasis mine:
It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the
window.onload
event. Each isolated world sees its own version of the object. Assigning to the object affects your independent copy of the object. For example, both the page and extension can assign towindow.onload
, but neither one can read the other's event handler. The event handlers are called in the order in which they were assigned.
So, to override a page-level listener, you need to inject your overriding code into the page context itself. This is possible; see this excellent answer for details, and here's an example:
var actualCode = "document.getElementById('loginForm').onsubmit = null;";
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
This adds a <script>
element to the page, which then executes in the page's own context.
Upvotes: 6
Reputation: 690
Try this:
window.addEventListener('submit', function(event) {
event.stopImmediatePropagation();
}, true);
It will stop the propagation of the event.
Upvotes: 0
Reputation: 1374
I actually don't know the object whose 'onSubmit' event is being processed here, so using pseudo logic here:
Hope this helps.
Upvotes: -1