Chrome Extension background scripts aren't being loaded - google-chrome

My chrome extension background script is not being loaded. I followed Googles guide for them but still nothing. I'm not sure if there is another way to check but it isn't in Inspect Element and what the script should be doing isn't happening.
http://developer.chrome.com/extensions/background_pages.html
manifest.json file
{
"manifest_version": 2,
"name": "WebDevFriend",
"description": "blah blah blah",
"version": "1.0",
"permissions": [
"bookmarks",
"tabs",
"http://*/*" ],
"background": {
"scripts": ["js/settings.js"],
},
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "html/popup.html"
}
}
settings.js file
chrome.windows.onCreated.addListener(function(window){
chrome.windows.getAll(function(windows){
var length = windows.length;
if (length == 2) {
chrome.tabs.executeScript(null, {file: "content_script.js"});
}
});
});
document.write('hello');

First you can't view the background page like a regular html page.
The only way is to view its contents with the Chrome Developer Tools.
just click on generated_background_page.html in the extensions section of your browser.
Second use the console.log() statement to log messages.

Related

chrome extension: Getting the source HTML of the current page on page load

I found this answer on how to grab the page source of current tab:
Getting the source HTML of the current page from chrome extension
However, this answer requires user to press the extension popup.
I would like to know how I can access the page source upon loading of page (without having to invoke the popup).
In my background.js I've tired this:
chrome.tabs.onUpdated.addListener(function (tabId , info) {
console.log(info)
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
});
but this results in the following error:
There was an error injecting script : Cannot access contents of the
page. Extension manifest must request permission to access the
respective host.
My manifest.js:
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["declarativeContent",
"https://www.example.com/*",
"storage",
"activeTab"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"options_page": "options.html",
"manifest_version": 2,
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
}
I don't think the issue is really with permissions because I am able to get the page source from the popup.html (which is page_action script). But I am not able to get it via "background" or "content_scripts". Why is that and what is the proper way to accomplish this?
It is about the permissions.
Your example a bit insufficient, but as I can see you are using "activeTab" permission.
According to the activeTab docs, the extension will get access (e.g. sources) to current tab after any of these actions will be performed:
Executing a browser action
Executing a page action
Executing a context menu item
Executing a keyboard shortcut from the commands API
Accepting a suggestion from the omnibox API
That's why you can get sources after opening the popup.
In order to get access to tabs without those actions, you need to ask for the following permissions:
tabs
<all_urls>
Be noted, it allows you to run content-script on every tab, not only the active one.
Here is the simplest example:
manifest.json
{
"name": "Getting Started Example",
"version": "1.0",
"description": "Build an Extension!",
"permissions": ["tabs", "<all_urls>"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"manifest_version": 2
}
background.js
chrome.tabs.onUpdated.addListener(function (tabId, info) {
if(info.status === 'complete') {
chrome.tabs.executeScript({
code: "document.documentElement.innerHTML" // or 'file: "getPagesSource.js"'
}, function(result) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
} else {
console.log(result)
}
});
}
});

Chrome Extension - Append HTML & Run jQuery Function on Extension Click

So I'm in the midst of creating my first Chrome Extension (Trying)
I feel like I'm close... But I genuinely don't know what to google to get the answers I need. So I'm sorry if this is a silly question.
Essentially what I'm trying to do is on click of extension - Append HTML & CSS to body and run a jQuery function. But from the looks of it, I need to call in jQuery in the manifest? Which I think I've done and it's still not working.
My Code:
manifest.json
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Hover Title",
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery-1.7.2.min.js", "background.js" ],
"matches": [ "http://*/*", "https://*/*"]
}],
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
(function ($) {
$('body').append("Hello");
alert("Hello");
console.log("Hello");
}(jQuery));
});
Any insight into where I'm going wrong would be massively helpful!
Thank you!!
Chrome extension architecture is simple but it doesn't mean one can write code without studying it.
There are two methods of injecting content scripts:
Unconditionally on all specified urls, in which case "content_script" key is used in the manifest and the content scripts communicate with the background page via runtime.sendMessage.
Only when some event occurs like e.g. the user clicks our toolbar icon, in which case we only need the permission to access the active tab.
So in the given case we'll attach the icon click handler and inject the code afterwards:
manifest.json:
{
"name": "Title",
"description": "Description",
"version": "1.0",
"browser_action": {
"default_title": "Icon Title",
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": ["activeTab"],
"manifest_version": 2
}
background.js (this is an event page because we didn't use "persistent": true in the manifest, so be advised that the [global] variables will be lost after a few seconds of inactivity; instead you should use chrome.storage API or HTML5 localStorage/sessionStorage/and so on):
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "jquery-1.7.2.min.js"}, function(result) {
chrome.tabs.executeScript({file: "content.js"}, function(result) {
});
});
});
content.js (the code runs in a sandbox so there's no need to hide global variables using IIFE)
$('body').append("Hello");
alert("Hello");
console.log("Hello");

Fire extension on very page Google Chrome Extension

I'm building a Google Chrome extension and want to autoload my extension on every new page, so that I can get the current url and check in a Database some data for it. I want to do it a bit like the adblockers and show how many ads where blocked with the badgetext. Anyway I don't get it workig to autoload on every new page I open. It loades once and then stays there. It only reloads when I click on the Icon to get the popup.html.
Here my Manifest:
{
"manifest_version": 2,
"name": "Some name",
"description": "Some desc.",
"version": "1.0",
"permissions": [
"tabs",
"background"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
My background.js looks like this
chrome.windows.onFocusChanged.addListener(function(){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
// do some stuff with the new url
});
});
Someone have a hint?
I would use chrome.tabs API instead of chrome.windows API.
http://developer.chrome.com/extensions/tabs.html
onCreated event and onUpdated event should work.
chrome.tabs.onCreated.addListener(function callback)
chrome.tabs.onUpdated.addListener(function callback)

Chrome extension: Cannot run code in chrome.tabs.executeScript in context of the page

I created an extension for Google Chrome with this background script background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {code:"document.body.style.background='red !important';"}); // doesn't work
chrome.tabs.executeScript(tab.id, {code:"alert('hello');"}); // runs alert
});
I want to run document.body.style.background='red !important'; in the context of the web page.
How can I do it?
manifest.json:
{
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"description": "Test",
"browser_action": { "default_icon": "icon.png" },
"background": { "scripts": ["background.js"] },
"permissions": ["tabs", "*://*/*"]
}
Plain and straight. Add https://*/* to permissions.
background actually expects everything, if you want to change the color use backgroundColor and need not give !important as you are injecting after everything is loaded.
So the below change may work. Please try that.
chrome.tabs.executeScript(tab.id, {code:"document.body.style.backgroundColor='red';"});

Background page function not triggered in google chrome:

I am using the following code to access the background page function in google chrome
popup.html
function sendRequest(ea,eb)
{
console.log("Inside");
chrome.extension.sendRequest({ea:ea,eb:eb},
function(response)
{
alert(response.farewell);
});
}
background.html
<html>
<body>
<script>
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
sendResponse({farewell: "goodbye"});
})
</html>
</body>
</script>
manifest.json
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"background": {
"page": "background.html"
},
"content_scripts": [
{
"matches": ["http://*/"],
"js": ["popup.js"]
}
],
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "mine.html"
},
"permissions": [
"tabs","http://*/","background"
],
"web_accessible_resources": ["loading.html","bu.png"]
}
However it does not print the alert. Can anyone tell me what i am doing wrong here?
Your HTML for background.html is extremely malformed and should be fixed;
<html>
<body>
<script>
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
sendResponse({farewell: "goodbye"});
})
</script>
</body>
</html>
Tags should be closed in the reverse order of them being open to maintain a correct hierarchy. Since you had not done so, the <script> element was malformed and contained invalid syntax </html></body> so would not be executed correctly.
Since you're using version 2 of the manifest you may want to consider abstracting the contents of this script element (ignoring all HTML) to its own file (e.g. background.js) and change your manifest to the following;
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"minimum_chrome_version": "18",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["http://*/"],
"js": ["popup.js"]
}
],
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "mine.html"
},
"permissions": [
"tabs","http://*/","background"
],
"web_accessible_resources": ["loading.html","bu.png"]
}
Notice that the background property now contains an array of strings representing JavaScript files to be loaded (in the order specified) in to a dynamically generated background page.
I've also set the minimum_chrome_version property to 18 as manifest version 2 should only be used when targeting this version of Chrome and above.
Developers should now only really need to use background pages instead of scripts when they need to support older versions of Chrome.
Edit
It just clicked that you're attempting to execute embedded JavaScript within your background page. Manifest version 2 introduces Content Security Policies which prohibit the execution of inline (e.g. onclick="showDialog();" and href="javascript:void(0);") and embedded JavaScript. This is why your background.html won't work and why background.js will. You will also want to ensure your popup.html doesn't contain any embedded JavaScript. The best workaround (and generally best practice anyway) is to abstract all JavaScript into its own file (e.g. popup.js) which is referenced by the HTML file. For example;
<script src="/popup.js"></script>