0

I am trying to send a message from injected code to background.js.

ContentScript.js

var g = document.createElement('script');
g.src = chrome.runtime.getURL('/js/buttonclick.js');
g.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(g);

buttonclick.js

var qsb = document.createElement("button");
document.body.appendChild(qsb);
qsb.addEventListener("click", submitT);
function submitT(e) {
    opSubmit('T');    // opSubmit() is a function in a webpage, it is why I injected this code
    window.onbeforeunload = null;
    window.scrollTo(0, 0);
    chrome.runtime.sendMessage({text: "hey"}, function(response) {
    });
}

background.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    console.log("Received %o from %o, frame", msg, sender.tab, sender.frameId);
    sendResponse("Gotcha!");
    chrome.action.setBadgeText( { text: 'X', tabId: sender.tab.id} );
    chrome.action.setBadgeBackgroundColor( { color: '#ef5350', tabId: sender.tab.id} );
    setTimeout(function () {
        chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
            uu = tabs[0].url;
            tt = uu.indexOf(e);
            vv = uu.indexOf(c);
            if (tt != -1 || vv != -1) {
                chrome.scripting.executeScript({
                    target: {tabId: sender.tab.id, allFrames: true},
                        files: ['/js/inject.js']
                    });
                chrome.action.setBadgeText( { text: 'O', tabId: sender.tab.id} );
                chrome.action.setBadgeBackgroundColor( { color: 'green', tabId: sender.tab.id} );
            };
        });
    }, 4000);   

});

However, when I run it, I get this error in console:

Uncaught TypeError: Cannot read properties of undefined (reading 'sendMessage')

Is it because I tried to execute sendMessage in an injected code? Then how can I change my code so that it will properly send Message?

Alternatively, sendMessage works fine if I call it from content script directly. Is there any way conten script can recognize button click from my injected button(qsb)? I tried adding

qsb.id = "qsb1" 

in buttonclick.js and

document.getElementid("qsb1")

in contentscript.js but it can't recognize my button and instead returns null.

Thanks!

  • Delete everything inside ContentScript.js and replace it with the contents of buttonclick.js, then delete buttonclick.js. Your mistake was that creating a script element runs the code as a page script not as a content script. – wOxxOm Sep 04 '22 at 06:08
  • @wOxxOm I have to access a function defined in the webpage(opSubmit()). I couldn't access that function directly in Content Script, so I followed Rob W's method: https://stackoverflow.com/questions/9515704/use-a-content-script-to-access-the-page-context-variables-and-functions/9517879#9517879 – Alternative415 Sep 04 '22 at 10:19
  • In that case see the notes at the beginning of that answer about messaging. – wOxxOm Sep 04 '22 at 12:54
  • @wOxxOm Thanks for the suggestion. Looked it up and applied it to my code. Now my injected script looks much cleaner. I learnt that injected script should be minimal as possible. Thanks! – Alternative415 Sep 05 '22 at 11:46

1 Answers1

0

Okay, I did it with the latter method. I just added window.onload = function() to make my buttons load first and then used getElementid. It recognized my button correctly.