views:

345

answers:

1

Hi,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 stroe 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?

A: 

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.

Grumdrig

related questions