[Chrome Extension] Try to Print Facebook Id Next to User Name


Continue the work I have done yesterday, instead of print in the console, the id will be printed next to the name of the user if the id is found. The following is the code:

manifest json:

manifest.json | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
  "manifest_version": 2,

  "name": "FBUrlId",
  "description" : "Try to get Facebook Id from URL change",
  "version": "0.1",

  "background": {
      "scripts": ["eventPage.js"]
  },

  "content_scripts": [
    {
      "matches": ["https://www.facebook.com/*"],
      "js": ["showid.js"]
    }
  ],

  "permissions": [
    "tabs"
  ]
}

background.js:

eventPage.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var reId = /^https:\/\/www\.facebook\.com\/profile\.php\?id=(\d+)$/;
var reUser = /^https:\/\/www\.facebook\.com\/([a-zA-Z0-9.]+)$/;
var lastUrlIsId = false;

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.hasOwnProperty('url')) {

    //console.log(changeInfo.url);

    // check if URL consists of username
    var resultUser = changeInfo.url.match(reUser);
    if (resultUser) {
      //console.log(resultUser[1]); // username
      if (lastUrlIsId) {
        //console.log(resultUser[1] + " : " + id);
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {name: resultUser[1], id: id});
        });
      }
    }

    // check if URL consists of Id
    var resultId = changeInfo.url.match(reId);
    if (resultId) {
      //console.log(resultId[0]); // URL
      //console.log(resultId[1]); // id
      id = resultId[1];
      lastUrlIsId = true;
    } else {
      lastUrlIsId = false;
    }

  }
});

showid.js:

showid.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    //console.log(request.name);
    //console.log(request.id);

    // wait page to be loaded
    var timerId = setInterval(function() {
      var n = document.querySelector("#fb-timeline-cover-name");
      if (n != null) {
        var idNode = document.createTextNode(request.id);
        n.appendChild(idNode);
        clearInterval(timerId);
      }
    }, 500);
  });

References:

[1]Message Passing - Google Chrome
[2]javascript - How to wait for another JS to load to proceed operation? - Stack Overflow
[3]Window setInterval() Method