getElementById not working in Google Chrome extension for <embed>

前端 未结 4 567
北海茫月
北海茫月 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:55

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

    default.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!

提交回复
热议问题