1

I've tried searching everywhere for an answer to this so forgive me if it's out there somewhere, I was unable to find it.

I'm writing a simple Chrome Extension which places buttons on a page which change the values of input items on that page.

Simplified version of my content.js file:

urlField = $('#someidonthepage');

function changeValue(){
    urlField.val('test');
}

When I execute this code in the console, it works fine and I am able to call that function. With my extension however, it only works when I declare urlField inside of the function.

This obviously wouldn't be a big deal if it weren't for the fact that I have a bunch of functions and variables and I feel like it would be really inefficient to declare all 10 of them inside of every function.

I have tried using "window." and other things I found online regarding Global variables but I'm starting to think this has more to do with Chrome Extensions than incorrect syntax because it works fine in console.

I'm pretty much just getting started with programming so please let me know if there's any other info I can provide!

Thanks in advance!

1 Answers1

2

The obvious reason would be that the element is (re)created by the webpage later after it's loaded.

So when the global variable is initialized at the moment the content script is injected it contains either an undefined value (if the element didn't exist) or an outdated version of the element, which is later recreated.

On the other hand, when you access the element from an event handler the actually existing element is selected.

The simplest solution would be to avoid using the global variables.

Otherwise take a look at:

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Really appreciate the response! I just tried run at document end and it didn't work. The page uses AJAX so I'm not sure if that has something to do with it. Are you saying that it's not a huge deal to declare the variables in each of the functions? Like I said, I don't know too much about programming. Thanks again – somegenericusername Oct 11 '15 at 13:56
  • 1
    Depends on how your code is organized. For example, you can define the variables as global but not assign a value `var globalElement;` then in your event handler assign the actual value without `var` like `globalElement = $("someelement")` and then you can use it. Or you can pass the local variable to all the functions as a parameter. – wOxxOm Oct 11 '15 at 14:44