Karl
Karl

Reputation: 531

How to remove an event listener via Chrome extension

I need to remove the following event listeners with my Chrome extension, after the page loaded.

Page content:

<input type="password" size="15" value="" autocomplete="off"
    onkeyup="javascript:vaciar(this)"
    onkeypress="javascript:vaciar(this)"
    onkeydown="javascript:vaciar(this)" name="password"
id="contrasena" />

The code in my content script is:

var password_field = document.getElementById("contrasena");
password_field.removeAttribute("onkeypress");
password_field.removeAttribute("onkeydown");
password_field.removeAttribute("onkeyup");
password_field.onkeypress = null;
password_field.onkeydown = null;
password_field.onkeyup = null;

For some reason, the event listeners keep active, but when I copy and execute the code in the console it works.

Upvotes: 2

Views: 788

Answers (2)

rms
rms

Reputation: 31

Are you putting your reset code in a body/onload function?

‹body onload="resetInput();"›
    ‹input type="password" size="15" value="" autocomplete="off" onkeyup="vaciar(this)" onkeypress="vaciar(this)" onkeydown="vaciar(this)" name="password" id="contrasena" /›
‹/body›

And declare the function

function resetInput(){
    var password_field = document.getElementById("contrasena");
    password_field.removeAttribute("onkeypress");
    password_field.removeAttribute("onkeydown");
    password_field.removeAttribute("onkeyup");
}

You don't need to unbind your event while they are inline events.

Upvotes: 0

Xan
Xan

Reputation: 77523

This fails because of the isolated context that context scripts live in.

To affect handlers set by the page's context, you need to inject the above code into the page.

See this question for a canonical explanation and examples.

Upvotes: 2

Related Questions