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!