I have created Chrome extension which should change page body color. It is working when I am clicking on the extension but I want it be done when the page loads, where an alert shows that controls is passing through code, it is not calling the function. Please help to fix this.
----------manifest.json-----------
{
"name": "My Page changer",
"description": "Make the current page red",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "Make this page blue"
},
"manifest_version": 2
}
------------------ background.js--------------------
debugger;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
debugger;
alert('I am here too ');
/*chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="blue"'
//code : 'doWhatYouWant()'
});*/
// Execute some script when the page is fully (DOM) ready
chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
}
});
function doWhatYouWant(){
alert('I am inside doWhatYouWant');
document.body.style.backgroundColor="blue";
}
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
// No tabs or host permissions needed!
alert('i am here');
console.log('Turning ' + tab.url + ' red!');
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="red"'
});
});
2 Answers 2
Your doWhatYouWant function lives in your background page, so you won't be able to call it from a content script.
If the code you want to run is more than a couple lines long, consider putting it into a file in your extension and using the file: field in the InjectDetails parameter when you invoke chrome.tabs.executeScript.
Also, if you want it to run on every page, you can declare it as a content script in your manifest, instead of having the chrome.tabs.onUpdated listener.
Comments
There is the "prince" example on google content script tutorial: https://developer.chrome.com/extensions/content_scripts.html#pi I tried when learning to "google-extenioning"(?) and it works fine. Good Luck!
eidt - uh, forgot, files are here
Comments
Explore related questions
See similar questions with these tags.