FitzFish
FitzFish

Reputation: 8629

Make queries and get source code with chrome extension

I want to create an extension for chrome that is near to the GmailChecker. I've seen its source code but hek, it's a bit complex. It seem to use some AJAX.

I've try to use jQuery, but it doesen't work in this case (can't access to website hosted on an other server... and as this is an extension for chrome, the script can't be executed from the same server).

By the way I'm not sure what I want to do is possible with it. I don't really know chrome extension well yet, so I need your help.

I want to proceed like that : In the background page, at regular intervals, load a page using cookies-session (for browsing into a website with login system). Then getting the source code of the loaded page, and doing some stuff then (like said to the user if he has message, but meh, this is not the topic nor the problem I think).

So I need at least :

Can I do this things with an Chrome Extension (and if yes, can you give me some function or tip to do it) ?

Thank you !!

Manifest :

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1",
  "description": "Yeah, cool ext",
  "browser_action": {
    "default_popup": "file.html"
  },
  "permissions": ["tabs",
  "background",
  "*://*.google.com/"],
  "background": {
    "page": "background.html"
  }
}

background.html :

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

<body>
    <script src='script.js'></script>
</body>
</html>

script.js :

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    console.log(xhr.responseText);   //that's the source code
};
xhr.open("GET", "http://www.google.com", true);
xhr.send();

Upvotes: 1

Views: 936

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Yea you can do those with a simple AJAX call:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    xhr.readyState == 4 && console.log(xhr.responseText);//that's the source code
};
xhr.open("GET", "http://www.google.com", true);
xhr.send();

Or in jQuery:

$.get("http://www.google.com/", function(data){
    console.log(data);
});

Since this is an extension, if you have correctly declared the sites you need access to in the manifest, you can perform a direct request to another site without they having cross origin resource sharing enabled. You do not need a server in the middle to perform the request for you and ajax your server to get the result back. This does not require JSONP.

Google has a page on cross-domain requests in extensions. You can read more here: https://developer.chrome.com/extensions/xhr#requesting-permission

By adding hosts or host match patterns (or both) to the permissions section of the manifest file, the extension can request access to remote servers outside of its origin.

Upvotes: 3

Related Questions