I’m trying to create a chrome extension. When the user clicks my extension’s icon (browserAction) the content script appends an extra div to the body of the open page(current tab). It works fine in all the sites except google’s search page and youtube. I’m not getting any error message or anything. It simply wont give any response.
This is my code in content.js:
alert('sdsd');
$('body').append("<div id='popup'>My extension name</div>");
I’ve put the alert for testing purpose. So when extension is toggled it should show an alert message followed by appending the div to body, ideally! But it wont for these 2 sites.
Any idea what could be going wrong here?
manifest
{
"name": "My first extension",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"content_scripts": [{
"all_frames": true,
"css": ["style.css"],
"matches": ["http://*/*","https://*/*"]
}],
"permissions": [ "tabs","http://*/*" ],
"browser_action": { "name": "test" },
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.executeScript(null,{file:"jquery.min.js"},function(){
chrome.tabs.executeScript(null,{file:"content.js"});
});
});
In Youtube’s page, $ is overwritten and isn’t jQuery. It’s
So your code makes an exception as there
document.getElementById('body')isundefined.You should try using noConflict().
EDIT :
Why aren’t you simply listing
jQuery.min.jsand yourcontent.jsin thecontent_scriptsinstead of injecting them programmatically. This would avoid conflicts.EDIT 2 :
Now that you use content scripts, you should use communication as described here to send from
background.jsto the content script the instruction to show the alert.EDIT 3 :
Another solution would have been to use programmatic injection (as you initially did) and not use jquery,
$('body').append("<div id='popup'>My extension name</div>");being translated in vanilla JS toBut it’s generally cleaner (and requires less permissions) to avoid programmatic injection.