Hick
Hick

Reputation: 36404

How to get a response out of chrome tab by its extension?

Suppose I open a new chrome tab for a user to sign in. The tab is opened by createTab from the chrome extension. And once the user signs in, and server sends a response, how would I make my chrome extension get the response data?

I am able to both create and delete the tab but I am not able to figure how to make my chrome extension know that the tab has got a response so that my chrome extension reads that response, stores it in local storage and removes/deletes the chrome tab.

Upvotes: 0

Views: 699

Answers (1)

Sudarshan
Sudarshan

Reputation: 18534

Suppose I open a new chrome tab for a user to sign in. The tab is opened by createTab from the chrome extension. And once the user signs in, and server sends a response, how would I make my chrome extension get the response data? I am assuming server sends response login pass\fail to page which is newly created by chrome.newTab. If my assumption is correct this structure for your functional requirement can help.

The content script injected will look for response received and notifies Chrome Extension; Chrome Extension can use data as needed.

enter image description here

manifest.json

{
  "name": "Content to Extension",
  "description": "A sample AJAX call and etc",
  "version": "0.1",
  "permissions": [
    "experimental", "tabs","<all_urls>"
  ],
  "browser_action": {
    "default_icon": "icon.jpg",
    "default_popup": "popup.html"
  },
  "manifest_version": 2,
  "content_scripts":[
  {
    "matches": ["<all_urls>"],
    "js":["content.js"]
  }
  ]
}

popup.html

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

content.js

function filtersearch(){

var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(data) {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
            console.log("message Sent");
            chrome.extension.sendMessage("Response recived");
        }
      } else {
        //callback(null);
      }
    }

var url = 'http://www.w3schools.com/html/default.asp';
xhr.open('GET', url, true);
xhr.send();

}
window.onload = filtersearch;

popup.js

chrome.extension.onMessage.addListener(function (message,sender,callback){
    console.log("Message Recieved");

    //Store in Local Storage
    localStorage.messageRecieved = message;

    // Close or remove tabs or Do every thing here
});

Let me know if you need more information.

Upvotes: 1

Related Questions