开发者

Chrome extension:Cannot call method 'getElementsByTagName' of null

开发者 https://www.devze.com 2022-12-24 03:19 出处:网络
i am beginner with chrome extension.There is simple problem. There is the code in my extension,but it do not work.I don\'t know how to figure it out.

i am beginner with chrome extension.There is simple problem. There is the code in my extension,but it do not work.I don't know how to figure it out. In my extension, i used a xml file to stro开发者_如何学Goe some data.There is the code in my background.html,but it do not work

    <!DOCTYPE html>
<html>
<head>
</head>

<body>
<script>
function loadXmlFile(){
   var xmlDom = null;
   var xmlhttp = new XMLHttpRequest();
       if( xmlhttp ){
               xmlhttp.onreadystatechange = function(){
                       if( xmlhttp.readyState == 4 ){
                            if( xmlhttp.status == 200 ){
                                       xmlDom = xmlhttp.responseXML;
                               }
                       }
               }
               xmlhttp.open( "GET",chrome.extension.getURL("/xml/123.xml"),true);
               xmlhttp.send( null );
       }
       return xmlDom;
}

var xmlDom = loadXmlFile();
var s = xmlDom.getElementsByTagName( "to" );
alert( s[0].nodeType );
</script>
</body>
</html>

I used developer tools to debug,but it says " Cannot call method 'getElementsByTagName' of null"... who can help me?


The return value of loadXmlFile is initialized to null and only set to something in the onreadystatechange callback, so at the time the function returns it is probably still null. Hence xmlDom is null on this line where you're getting your error:

var s = xmlDom.getElementsByTagName( "to" );

That line and the alert should be within the innermost block of your onreadystatechange callback.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号