How to create functions for extension

1

I'm creating an extension, my first extension to Google Chrome, the extension consists of changing elements of a page and changing things, but I wanted to put a function for a button via onclick , but it does not work! Assuming that the site has the following structure HTML:

<button class="one" onclick="funcaoOriginal();">Teste</button>

In the file js of the extension I have the following:

function minhaFuncao(){
alert('teste');
}

$('.one').attr('onclick','minhaFuncao()');

but does not work !, if so:

$('.one').attr('onclick','alert(\'teste\')');

It works, but I want to put things like $.each and $.cookie inside a function and call it by clicking the site button.

How would I do this?

    
asked by anonymous 28.06.2015 / 00:34

1 answer

1

When you have inline function calls in HTML then these functions must be in global scope. If you put in another function like .ready() then they are only accessible within that function and no longer in the global scope.

You have two alternatives:

  • put in global scope and keep the inline function call in HTML

HTML:

<button class="one" onclick="funcaoOriginal();">Teste</button>

JavaScript:

function minhaFuncao(){
    // fazer algo
}
$(document).ready(function(){
    // resto do código...
  • use an event dropper

In this case, you can remove onclick="funcaoOriginal();" from HTML and use

 $('.one').on('click', function(){
     // código
 });

or using the role declared

$('.one').on('click', minhaFuncao);

This second alternative is better. Mixing inline in HTML is not a good solution. If you use $('.one').on('click', minhaFuncao); remember that this line and the function declaration must be in the same scope. They can both be within .ready() or another block of code, but must be in the same scope.

    
28.06.2015 / 09:03