问题
I'm try to develop a simple google chrome extension. What it does it that it displays the number of downloads on a page (the count) and display it in a popup.
The page in question that needs monitoring is a page which can only be acessed after logged in.
So I need to basically use html and javascript to 'scrap' the count number from the page and display it in a popup. So far I have created the barebones of the exntension:
{
"name": "Downloads Logger",
"version": "1.0",
"manifest_version": 2,
"description": "Monitors Number Of Downloads",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"http://exampledownloadpage.com/loggedin/"
]
}
What do I do next? Do I need a background page for the extension? I have read up the extensions documentation and unpacked the official gmail extension and try seeing how it works, but it seems to make use of 'feeds' to get it's data. Can anybody point me in the right direction? Thank you in advance!
回答1:
If you only want to display the number of downloads in a browser_action then you shouldnt need a background page, but if you wanted to monitor the amount of downloads every minute or so then you would. To get the download count you could use XMLHttpRequest to download the pages source, then parse it to a dom using.....
var page = document.implementation.createHTMLDocument("");
page.documentElement.innerHTML = pageSource; // assuming the source for the page you downloaded with httprequest is in pageSource
...and then you could use something like querySelector to get the text of the bit of the page your intesersted in, something like.....
downloadstats = page.querySelector('.downloadstats').textContent.trim();
Hopefully that'll get you started.
Here's a simple (no error checking or what not) example that gets your rep points from stackoverflow.....
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
var page = document.implementation.createHTMLDocument("");
page.documentElement.innerHTML = this.responseText;
var score = page.querySelector('[title^="your reputation;"]').textContent.trim();
alert('You have ' + score + ' rep points.');
}
}
xmlhttp.open("GET", "http://stackoverflow.com", true);
xmlhttp.send();
来源:https://stackoverflow.com/questions/10871680/getting-snippet-of-text-from-external-page-into-google-chrome-extension