Skip to content Skip to sidebar Skip to footer

Getelementbyid Not Working In Google Chrome Extension For

In my Google Chrome extension content script I have the following: jQuery(document).ready(function() { var player = document.getElementById('player'); console.log(player);

Solution 1:

Direct executing DOM related operation in JS is not correct. For example:

default.html

<!DOCTYPE HTML><html><head><scripttype="text/javascript"src="default.js"></script></head><body><aid="Bar"href="#"></a></body></html>

default.js

const bar = document.getElementById("Bar");
alert(bar.id);

At this time the DOM content may not be completely loaded yet, and that is why the "bar" may be "NULL".

The correct way to do this is:

default.js

document.addEventListener('DOMContentLoaded', function() {
  const bar = document.getElementById("Bar");
  alert(bar.id);
  });

That is: executing the DOM related operation when the DOMContentLoaded event happens.

"setTimeout" is not the right way because you cannot make sure the DOM content is completely loaded by setting some time delay!

Solution 2:

Turns out the problem was with timing. Even though it was inside a jQuery(document).ready(), the getElementById failed because the embed wasn't loaded yet. When I do a setTimeout of a few seconds, the getElementById works.

Solution 3:

Works fine for me in chrome 9.

Try this fiddle: http://jsfiddle.net/Ee7mq/

If the console doesn't show the player tag something is wrong with your browser. If it does, something is wrong with your code. To figure out what i'd need to see more of it.

Solution 4:

Use defer.

<scriptdefer>...</script>

Post a Comment for "Getelementbyid Not Working In Google Chrome Extension For "