getElementById not working in Google Chrome extension for <embed>

前端 未结 4 563
北海茫月
北海茫月 2021-01-07 12:52

In my Google Chrome extension content script I have the following:

jQuery(document).ready(function() {
    var player = document.getElementById(\'player\');
         


        
相关标签:
4条回答
  • 2021-01-07 13:33

    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.

    0 讨论(0)
  • 2021-01-07 13:36

    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.

    0 讨论(0)
  • 2021-01-07 13:55

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

    default.html

    <!DOCTYPE HTML>
    <html>
        <head>
        <script type="text/javascript" src="default.js"></script>
        </head>
        <body>
             <a id="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!

    0 讨论(0)
  • 2021-01-07 13:57

    Use defer.

    <script defer>...</script>
    
    0 讨论(0)
提交回复
热议问题