0

I am working on a Chrome extension whose goal is to access a website in the background a display a specific value from it which the user should see by clicking on the chrome extension icon without having it to open the specific tab.

Here's my popup.html :

<!doctype html>
<html>
  <head>
    <title>Notification Analyzer</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Current Notifications</h1>
    <a id="myLink" href ="https://website.com/notify/index.php"></a>
  </body>
</html>

And my popup.js :

a = document.getElementsByClassName('notificationArea').item('span').childNodes[6].textContent; // this is the value which I want to display on click of the extension icon

window.onload = function() {
   document.getElementById("myLink").innerHTML=a; 
} // Here, trying to add the value to the popup.html element 

If I try to popup as an alert box on the specific website tab, it works. But not in background when the website tab is not open.

So two problems here :

  1. How can I make the extension able to access the website contents in the background ?

  2. How can I show the javascript content from popup.js in the popup.html

1 Answers1

0

Question #1

You could use content scripts to access web pages, get the info and pass it to background page via messaging passing.

Question #2

Part I

It is the same with question #1 in fact. The following code should belong to content script

a = document.getElementsByClassName('notificationArea').item('span').childNodes[6].textContent; // this is the value which I want to display on click of the extension icon

Part II

Then you can use "message passing" cited above to pass it from content script to background page.

And since popup.js and background page both live in the extension process, there are many ways to communicate between each other. You can refer to previous post for more details. How to communicate between popup page and background page and store the info that I already get?

Part III

Finally you can use your code in popup.js to set the text of the link.

window.onload = function() {
    document.getElementById("myLink").innerHTML=a; 
} // Here, trying to add the value to the popup.html element

Appendix

To get the value you want to display, you can also just make a ajax call to the website, query the returned DOM and retrieve the data you want. All this can be done via popup.js. Sample code would look like

$.ajax({
    url: url,
    callback: function (data) {
        var mydata = $(data).find('You css selector');
        document.getElementById("myLink").innerHTML=mydata; 
    }
});
Community
  • 1
  • 1
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
  • I don't like this answer for only mentioning ("you need to") content scripts as a possibility to scrape information off pages. Often (but not always) XHR can solve this without having to open a tab. – Xan Mar 10 '16 at 09:51
  • @Xan, thanks for mentioning that, I'll update the answer – Haibara Ai Mar 10 '16 at 10:00