Search code examples
javascriptgoogle-chromexpathgoogle-chrome-extensiondocument.evaluate

Evaluating xpath expression in Chrome


I'm trying to extract a few rows from the table from this page http://www.money.pl/pieniadze/ using xpath expression and javascript. I can get the whole page being displayed as a pop-up but I cannot evalute xpath expression with document.evaluate(); Have tried to play with XPathResultType but no results. Can anybody help?

Here is my background page:

<html><head><script>
...
var wholePage;
setInterval(fetch, 20000);


    function fetch()
    {
        req = new XMLHttpRequest();
        var url = "http://www.money.pl/pieniadze/";
        req.open("GET", url);
        req.onload = process;
        req.send();
    }   

    function process()
    {
        wholePage = req.responseText;
    }
</script></head></html>

and here is the popup page:

<html><head><script>
...
    onload = setTimeout(extract, 0); 

        function extract()  
        {
            chrome.browserAction.setBadgeText({text: ''});
            var bg = chrome.extension.getBackgroundPage();
            var EurPlnPath = "//tr[@id='tabr_eurpln']";
            var tempDiv = document.getElementById('current');
            tempDiv.innerHTML = bg.wholePage;
            var oneTopic = document.evaluate( EurPlnPath, bg.wholePage, null, XPathResult.ANY_TYPE, null)
            var res = oneTopic.iterateNext();
        }

</script></head>
<body>
<div id="current">
</div>
</body>
</html>

Solution

  • You can't use XPath on plain strings. You have to convert the string into a document first. For example, using the DOMParser. Current browsers do not support text/html yet. To get this to work, you have to include the code as specified at this answer:

    var bgWholePage = new DOMParser().parseFromString(bg.wholePage, 'text/html');
    document.evaluate( EurPlnPath, bgWholePage, ...
    

    If you want to parse the document at the background page, use bg.document.evaluate instead of document.evaluate:

    var oneTopic = bg.document.evaluate( EurPlnPath, bg.wholePage, null, XPathResult.ANY_TYPE, null)