jValls
jValls

Reputation: 39

JS variable from DOM chrome extension

I would like to take some js variable using a injected script into the DOM. To do so I have two files the one that inject the script into the DOM and the one that send over the value.

getPageSource.js

var s = document.createElement('script');
    s.src = chrome.extension.getURL('script.js');
    (document.head||document.documentElement).appendChild(s);
    s.onload = function() {
    s.parentNode.removeChild(s);
};

function getTag(){
    document.addEventListener('ITAG_connectExtension', function(e) {
    return e.detail;
});}

chrome.extension.sendMessage({
    action: "getSource",
    source: getTag()
});

script.js

var tagType = {};
tagType = itsClickPI;
setTimeout(function() {
    document.dispatchEvent(new CustomEvent('ITAG_connectExtension', {
        detail: tagType
    }));
}, 0);

However the request.source in the popup.js is undefined.

popup.js

chrome.extension.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

Could you give me some lights on here?

Thanks in advance.

Upvotes: 0

Views: 126

Answers (1)

Xan
Xan

Reputation: 77482

Your problem is with getTag() function - it is asynchronous and cannot possibly return e.detail.

Even then the logic is suspect - you're adding an event listener, but you're triggering the event before it.

So what's the intended flow?

  1. Get ready to receive a reply.
  2. Inject a script that sends the data (that we are ready to receive).
  3. Send that data somewhere else.

The correct chain of events would be this:

function sendTag(tag) {
  // chrome.extension.sendMessage / onMessage are deprecated!
  chrome.runtime.sendMessage({
    action: "getSource",
    source: tag
  });
}

// 1. Get ready to listen
document.addEventListener('ITAG_connectExtension', function(e) {
  // This code executes asynchronously only when the event is received, so:
  // 3. Send the data
  sendTag(e.detail);
});

// 2. Inject the script
var s = document.createElement('script');
    s.src = chrome.extension.getURL('script.js');
    (document.head||document.documentElement).appendChild(s);
    s.onload = function() {
      s.parentNode.removeChild(s);
    };

If you need to do it several times, you only need to inject the script again (as the listener is ready).

Again, use chrome.runtime.onMessage on the receiving side.

Upvotes: 1

Related Questions