First I made a query from popup
requestForCodeMirrorElement(){
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {name: "GetChosenCodeMirrorText"}, (response) => {
console.log(response);
});
});
}
Then I add this in my content_script
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.name == "GetChosenCodeMirrorText"){
var codeMirrorContent='empty';
document.addEventListener('GetContent', function (e){
codeMirrorContent =e.detail.content;
console.log(codeMirrorContent);
sendResponse({chosenCodeMirrorText: codeMirrorContent});
});
var s = document.createElement('script');
s.src = chrome.extension.getURL('get_codemirror_script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};
}
return true;
});
I wrote this file called get_codemirror_script.js and it has been added to manifest.json.
When I test the code in Chrome, I get codeMirrorContent in console so I think get_codemirror_script.js does not have any problem.
When I change my content_script to this:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.name == "GetChosenCodeMirrorText"){
var codeMirrorContent='empty';
sendResponse({chosenCodeMirrorText: "forTest"});
document.addEventListener('GetContent', function (e){
codeMirrorContent =e.detail.content;
console.log(codeMirrorContent);
});
var s = document.createElement('script');
s.src = chrome.extension.getURL('get_codemirror_script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};
}
});
I get "forTest" in popup console. So I guess there should be some problem with sendRequest. How can I fix it?
UPDATE: Just for reference, I used to inject embedded code (see Insert code into the page context using a content script) instead of injecting file like what I described above. And that time it works fine.