1

I'm trying to make an extension that activates when I visit facebook. Up to this part all is good, however then it starts running my code indefinitely.

What I want is to run the content.js script only the first time I visit Facebook and then never run it again.

My current approach is this, but it doesn't work:

background.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.storage) {
    if (typeof request.value != 'undefined') {
      localStorage[request.storage] = request.value;
    }
    sendResponse({storage: localStorage[request.storage]});
  } else {
    sendResponse({});
  }
});

content.js

var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
  status = response.storage;
});

if(status != '1')
{
   chrome.extension.sendRequest({storage: 'status', value: '1'});
   //  do my stuff here but only 1 time
}

manifest.json

   "content_scripts": [ {
      "js": [ "js/jquery.js", "content.js" ],
      "matches": [ "https://facebook.com/" ]
   } ],

Basically my idea is to run content.js when I visit Facebook, then after the script is done, I add a status variable and then next time I check if the status is 1 which means that the code had already run before.

How can I accomplish this?

Thank you.

lincher
  • 45
  • 1
  • 1
  • 7
  • P.S. I answered _and_ closed as duplicate, because my other comments are slightly too big for the comments section. – Xan Jul 19 '15 at 13:38

1 Answers1

1

1) You are making the standard async JavaScript mistake.

var status;
chrome.extension.sendRequest({storage: 'status'}, function(response) {
  status = response.storage; // <--+
});                          //    | This code didn't execute yet
                             //    |
if(status != '1') // --------------+
{
   chrome.extension.sendRequest({storage: 'status', value: '1'});
   //  do my stuff here but only 1 time
}

2) You are using a very old and deprecated version of Messaging. extension.sendRequest/onRequest need to go, replacement is runtime.sendMessage/onMessage.

3) It's best to not use Messaging here at all; chrome.storage API is made specifically for this purpose. Again, maybe you're using some very old tutorial.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206