I'm trying to develop a chrome extension, it has to inject the script using OnUpdated
and OnActivated
Event Listener.
My script is injecting properly but the problem is that how I can communicate with my background/service_worker script using my injected script
This is image of my injected script which contain some kind of buttons Injected Script
I've tried to access these element into content-script send message to background/service_worker but these elements aren't accessible in my content-script
When I try to access element without injected script these elements are passing message correctly between content-script to background/service-worker Web page
This is the Manifest MV3
Manifest.json
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"css": [
"css/all.min.css",
"css/camera.css"
],
"js": [
"js/content-script.js"
],
"run_at": "document_end",
"all_frames": false
}
],
"web_accessible_resources": [
{
"resources": [
"*"
],
"matches": [
"<all_urls>"
],
"use_dynamic_url": true
}
]
This is my content-script.js
var startRecording = document.getElementById('start-recording');
var stopRecording = document.getElementById('rec-stop');
if(startRecording){
startRecording.addEventListener('click',()=> {
chrome.runtime.sendMessage({recording_started: true}, function(response){
console.log(response.result);
})
})
}
if(stopRecording){
stopRecording.addEventListener('click',()=>{
console.log('im stop')
})
}
startRecording
is accessing element from non injected script which is working and stopRecording
is accessing element from injected script which is not working well
and after all this is my service_worker.js which i'm using to listening messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Service Workder ',message);
if(message.recording_started){
sendResponse({result: 'hello Im going from service worker'});
}
if(message.notification){
sendResponse({result: 'Notification from service worker'});
}
})
Basically my problem is to accessing the element of injected script in content-script
and pass message to service_worker.js
when injected element is clicked
This is how I'm injecting my script
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == 'complete' && tab.status == 'complete' && tab.url !== 'undefined'){
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
if(tabs[0].url?.includes('chrome://')) return undefined;
var currentId = tabs[0].id;
chrome.scripting.executeScript({
target: {tabId: currentId, allFrames: false},
files: ['js/camera.js'],
});
});
}
})
Maybe I'm using the wrong method for message passing You should suggest me a better way to passing message between injected script and content-script Thanks