Error thrown when executing chrome.extension.getBackgroundPage() - google-chrome-extension

I am working on my first extension and am trying to create a simple extension to inject a draggable div on a page. That works nicely, but I want to preserve the location of the div on the background page (I'm also trying out local storage, but want to understand why this isn't working).
I do not need a button so have not created a popup.html file, which, I believe, is entirely optional. It certainly has worked so far just injecting javascript files.
However, I now get the following error thrown when executing chrome.extension.getBackgroundPage():
Uncaught Error: chrome.extension.getBackgroundPage can only be used in extension processes. See the content scripts documentation for more details.
The content scripts documentation did not seem to identify anything wrong with my approach: http://code.google.com/chrome/extensions/content_scripts.html
Here is a redacted manifest I am using:
{
"name": "My helper",
"version": "1.0",
"description": "Tastes great",
"background_page": "background.html",
"content_scripts": [
{
"matches":["https://page.of.interest/*"],
"run_at":"document_idle",
"js":[ "jquery.js", "jquery-ui-1.8.17.custom.min.js", "my_content_script.js"],
"css": [ "my_content_script.css" ]
}
],
"permissions": [
"background"
]
}
So I am running this statement inside "my_content_script.js". Is this NOT considered part of the extension process? Can I only run this on a popup.html (or other possibly?) file?
If this is the case, then maybe it is easier to just use localstorage rather than trying to communicate through the dom with the extension process.
Hope I've been clear despite my ignorance about some of these concepts.

I don't think the docs explicitly say you can't use chrome.extension.getBackgroundPage() from a content_script but because the content_script has permissions more oriented with the page it is being run on it isn't allowed access. The docs do mention a few methods you can use however.
Unlike the other chrome.* APIs, parts of chrome.extension can be used by content scripts:
You will have to use message passing to communicate between the background_page and the content_script.

You have to use the chrome.cookies.get() in background.html, and then do the communication between your content script and background.html for exchanging cookie data.

Related

How to programmatically enable flash in Chrome? [duplicate]

chrome.tabs returns undefined despite the fact I set tabs in the permissions block.
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"js/myScript.js"
],
"all_frames": true
}
],
But in myScript.js the following returns undefined.
chrome.tabs
As content script has its own limitations,
chrome.tabs is only available in background scripts and popup scripts.
If you wanna to use chrome.tabs then pass message from content_script to background script and play with chrome.tabs.
Content scripts have only limited access to Chrome APIs. This access does not include the API you are trying to use (e.g. chrome.tabs). If you need to use that API, you will have to do so in a background script1.
As listed in Chrome's content scripts documentation, the APIs available to a content script are [I have placed deprecated methods in strikethrough format]:
extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
i18n
runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
storage
A couple of the listed APIs are deprecated and have been for some time. Those that are deprecated have moved to different locations (also listed above):
extension.onRequest ➞ runtime.onMessage
extension.sendRequest ➞ runtime.sendMessage
While not officially deprecated, extension.lastError is also available as runtime.lastError. At this point, it is usually referred to at that location:
extension.lastError ➞ runtime.lastError
Partition your extension into background scripts and content scripts
You are going to need to separate your code into what needs to be in a background script and what needs to be in content scripts, based on the capabilities available to each type of script. Content scripts have access to the DOM of the web page into which they are injected, but limited access to extension APIs. Background scripts have full access to the extension APIs, but no access to web page content. You should read the Chrome extension overview, and the pages linked from there, to get a feel for what functionality should be located in which type of script.
It is common to need to communicate between your content scripts and background scripts. To do so you can use message passing. This allows you to communicate information between the two scripts to accomplish things which are not possible using only one type of script.
For instance, in your content script, you may need information which is only available from one of the other Chrome APIs, or you need something to happen which can most appropriately (or only) be done through one of the other Chrome extension APIs. In these cases, you will need to send a message to your background script, using chrome.runtime.sendMessage(), to tell it what needs to be done, while providing enough informaiton for it to be able to do so. Your background script can then return the desired information, if any, to your content script. Alternately, you will have times when the processing will primarily be done in the background script. The background script may inject a content script, or just message an already injected script, to obtain information from a page, or make changes to the web page.
Background script means any script that is in the background context. In addition to actual background scripts, this includes popups and options pages, etc. However, the only page that you can be sure to have consistently available to receive messages from a content script are your actual background scripts defined in manifest.json. Other pages may be available at some times as a result of the user's interaction with the browser, but they are not available consistently.
This answer was moved from a duplicate question, and then modified.
https://developer.chrome.com/extensions/tabs#method-getSelected shows
getSelected
chrome.tabs.getSelected(integer windowId, function
callback)
Deprecated since Chrome 33. Please use tabs.query {active: true}.
Gets the tab that is selected in the specified window.
Maybe, you should use chrome.tabs.query in popup.js like this
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
console.log(tabs[0].url);
});
, reload your extension and check the result in the inspect element of your extension.
result image
code image
https://developer.chrome.com/extensions/tabs#type-Tab shows that
The URL the tab is displaying. This property is only present if the extension's manifest includes the "tabs" permission.(Just for remind someone forgot. I was forgot it when I just test it.)
Check this answer also https://stackoverflow.com/a/6718277/449345
This one worked for me
chrome.tabs.getSelected(null, function(tab){
console.log(tab);
});

Background script only for specific domain in Chrome extension

I would like to know how to run the background script of a Chrome extension for only specific/specified domain/s please?
For example, if an extension is meant to run only on pages of Google.com, so there is no reason to keep the background script running on any other domains.
In my manifest file I have set "matches" but I can still see the background script running on every domain and tab.
...
"background": {
"matches": [
"*://*.google.com/*"
],
"scripts": ["scripts/background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"*://*.google.com/*"
],
"css": ["styles/default.css"],
"js": ["scripts/jquery.js", "scripts/default.js"]
}
],
"permissions": [
"storage",
"declarativeContent",
"tabs"
],
...
Edit
To add more info that will help understand my goal:
I have a content script and a popup, the popup is being used as a remote control with options to choose from and play with, that will eventually effects the page.
When changing an option in the popup, it sends it's value to the background/event script, there it being temporary saved in a variable, and then being sent to the content script, where it actually being executing and show up on the page to the user.
And I want that only when the user leaves the specific domain, the background/event script will save the settings to storage, so by that there will be only a single storage saving task and NOT each time the user is changing a setting in the popup.
After the settings got saved to storage and the user left, I want nothing to run it the background anymore please.
You are misunderstanding what the background page is for, and what "persistent": false means.
The background page does not run "for" any domain; it just runs. A single copy per extension. Have a look at the Architecture Overview.
However, if you are concerned that it consumes resources, you add "persistent": false to the manifest. This makes it an Event page, that is unloaded when it's not doing work.
If your event page is woken up only by content scripts, then you have achieved your goal: it won't be running when it's not needed.
It's entirely up to you to properly construct the background page so it's idle when you don't need it. Since you haven't told what it's supposed to be doing - well..
Do read the Event page documentation, there are important restrictions you need to understand.

How to inject javascript into Chrome DevTools itself

Ok, so just the other day I learned that you can inspect the devtools if it is in its own window(explained here). I also learned that you can style the devtools with your own css by editing the Custom.css file in your profile on your computer(more on that here).
What I want to do is not only add css, but also javascript, via a chrome extension. I am very aware of devtools pages, but those do not do what I want. Pretty much I want to get a content script to run on the devtools inspector itself. I found one extension that does exactly this, but for the life of me I have not been able to replicate it(even when copy-pasting the code!!). The extension is the "Discover DevTools Companion extension" from Code School(on the webstore). They even explain how it works, but I still have had no luck. That was the only extension I have found that does what I want. So I guess what I'm really asking is if its just me that cannot get it to work or if others that try are having trouble also.
Usually, you cannot create a Chrome extension which injects code in a devtools page.
The "Discover DevTools Companion" extension from now on, referred to as DDC is allowed to do this, because this extension is whitelisted in the source code of Chromium: (this is no longer the case)
// Whitelist "Discover DevTools Companion" extension from Google that
// needs the ability to script DevTools pages. Companion will assist
// online courses and will be needed while the online educational programs
// are in place.
scripting_whitelist_.push_back("angkfkebojeancgemegoedelbnjgcgme");
If you want to publish an extension in the Chrome Web Store with these capabilities, give up.
If you want to create such an extension for personal / internal use, read further.
Method 1: Impersonate the DDC a whitelisted extension
The easiest way to create an extension with such permissions is to create an extension with the extension ID of a whitelisted extension (e.g. ChromeVox). This is achieved by copying the "key" key of its manifest file to your extension's manifest (see also: How to get the key?). This is a minimal example:
manifest.json
{
// WARNING: Do NOT load this extension if you use ChromeVox!
// WARNING: Do NOT load this extension if you use ChromeVox!
// WARNING: This is a REALLY BIG HAMMER.
"content_scripts": [{
"js": [ "run_as_devtools.js" ],
"matches": [ "<all_urls>" ]
}],
// This is the key for kgejglhpjiefppelpmljglcjbhoiplfn (ChromeVox)
"key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEGBi/oD7Yl/Y16w3+gee/95/EUpRZ2U6c+8orV5ei+3CRsBsoXI/DPGBauZ3rWQ47aQnfoG00sXigFdJA2NhNK9OgmRA2evnsRRbjYm2BG1twpaLsgQPPus3PyczbDCvhFu8k24wzFyEtxLrfxAGBseBPb9QrCz7B4k2QgxD/CwIDAQAB",
"manifest_version": 2,
"name": "Elevated Devtools extension",
"version": "1.0"
}
run_as_devtools.js
if (location.protocol === 'chrome-devtools:') (function() {
'use strict';
// Whatever you want to do with the devtools.
})();
Note: This method is truly a hack. Since the extension shares the same ID as ChromeVox, both extensions cannot co-exist. And if Chrome decides to remove the whitelisted extension, then your permissions will evaporate.
Instead of filtering via the content script, you can also use the include_globs key to restrict the content script to devtools only.
Method 2: Modify resources.pak
I suggest to go with method 1 if possible. When method 1 fails (e.g. because the extension is no longer whitelisted), use the next method.
Get paktools.py, unpack.py and pack.py from DennisKehrig/patch_devtools (on Github).
Locate your Chrome directory containing resources.pak.
Run python2 unpack.py resources.pak, which creates a directory resources containing all files (all file names are numbers).
Locate the file containing a script which runs in the context of the developer tools. Add your desired code there.
Remove resources.pak
Run python2 pack.py resources to create the new resources.pak file.
Note: resources.pak may be replaced when Chrome is updated, so I suggest to create a script which automates my described algorithm. That shouldn't be too difficult.
If you're interested, you can look up the .pak file format in ui/base/resource/data_pack_literal.cc (description in human language).
For those googlers who end up at this page (as I did) looking for something else, this page answers the question of manipulating DevTools ITSELF - not adding jQuery to DevTools, or injecting javaScript onto a web page. For those, see here instead:
Inject jQuery into DevTools (Chrome or Firefox):
Firefox DevTools: Automatically injecting jQuery
Inject your own javascript/css onto any web page:
How to edit a website's background colors

Chrome extension using sidebar

I've been having a look at Chrome extensions and I'd like to create an extension that interacts with a web page using a sidebar. So, user clicks button to launch extension, and the current page splits, with the right hand portion displaying my extension. I tried below, but I see nothing (working or otherwise). I'm not overly surprised it's not working as I do not have a sidebar.html file for one thing. The reason I have that in the manifest is because I saw it in another post in this site. The suggestion there was to use the "sidebar" line in manifest.json, but "sidebar" isn't even mentioned in the documentation as being a valid part of the manifest syntax.
manifest.json:
{
"name": "Test 1",
"version": "1.0",
"description": "Test Extension 1",
"page_action": {
"default_icon": "icon.png",
"default_title": "Testing",
"default_popup": "popup.html"
},
"sidebar" : {},
"permissions": [
"experimental"
]
}
popup.html:
<script>
chrome.experimental.sidebar.show();
chrome.experimental.sidebar.expand();
chrome.experimental.sidebar.navigate({path: "sidebar.html"});
</script>
I've enabled 'experimental'.
Thanks for any help.
The problem is that you are opening, theoretically, the sidebar inside your popup, not in the current page.
You should add a content script in the page, with a function that opens the sidebar. So, in your popup you should just retrieve the current tab then call this function from it.
Also, as Boris Smus said in your question, sidebars will be discontinued in future versions. So I advice you to create your own sidebar frame via content scripts.
Update
To help you, I've made a simple extension that create a sidebar on current page.
#Curtis hosted my sample extension on Github, you can clone it here.
I was looking for a sidebar solution as well and ended up at
Implement chrome.sidebar API thread.
According to the Sidebar PRD, it is already possible to create sidebar by:
injecting a script into the page which edits the HTML of the page to display a sidebar by modifying the DOM to insert an iframe which
loads the contents of the sidebar from a remote server.
the injected script can edit the DOM directly to display a sidebar, the contents of which are passed via message.
However, there are many downsides (explained in the same document) with regard to:
Usability, Performance, Security, Privacy (Extension sniffing as well as Third party cookies) and Accessibility.
You can watch a demo of what they are preparing for future Sidebar Component.
It might help in shipping the feature quicker if you star the thread.
update
Per this comment, Chrome will not get a built-in sidebar component.

chrome.tabs.executeScript not working?

I am trying to learn to use the chrome.tabs.executeScript commend. I've created a simple extension with a browser action. My background.html file currently looks like this:
<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null,{code:"document.body.bgColor='red'"});
chrome.tabs.executeScript(null, {file: "content_script.js"});
});
</script>
</html>
The "content_script.js" file contains document.body.bgColor='red'.
When pushing the browser action's button nothing happens. Obviously I'm missing something very basic.
I've checked with console.log that indeed control reaches the chrome.tabs.executeScript calls when the browser action is pressed. Otherwise I'm not sure how to even check if my content script's code is run (it seems not; console.log I put in the content script has no effect, but maybe it shouldn't have one even if the script is run successfully).
Make sure you have domain and tab permissions in the manifest:
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
Then to change body color try:
chrome.tabs.executeScript(null,{code:"document.body.style.backgroundColor='red'"});
Also keep in mind that content scripts are not injected into any chrome:// or extension gallery pages.
For those of you still having issues, you need to make sure to reload the extension's permissions in Chrome.
Go to chrome://extensions , scroll to your extension, and click on "reload". Make sure that your permissions have been updated by clicking on the permissions link right next to your extension.
You actually don't need and don't want the 'tabs' permission for executeScript.
"permissions": [
"http://*/*",
"https://*/*"
]
Should be enough.
It's not recommended to use http://*/* and https://*/*. From the Google documentation:
To inject a programmatic content script, provide the activeTab permission in the manifest. This grants secure access to the active site's host and temporary access to the tabs permission, enabling the content script to run on the current active tab without specifying cross-origin permissions.
Instead, (as suggested in the page) just use activeTab permission.
Remark: more explanation for the security issue
Without activeTab, this extension would need to request full, persistent access to every web site, just so that it could do its work if it happened to be called upon by the user. This is a lot of power to entrust to such a simple extension. And if the extension is ever compromised, the attacker gets access to everything the extension had.
In contrast, an extension with the activeTab permission only obtains access to a tab in response to an explicit user gesture. If the extension is compromised the attacker would need to wait for the user to invoke the extension before obtaining access. And that access only lasts until the tab is navigated or is closed.
(emphasis mine)
In the example code posted by the OP, activeTab is sufficient.
However, if the extension is more complex and needs to work "automatically" (i.e. without the user clicking the button); then this method will not work and additional permission is required.
Most of the answers above seems to be working fine for manifest version 2 but when it comes manifest-3 their seems to be some workaround to make the content-script load in the latest manifest 3.We need to use the following steps to execute content script in manifest 3
First adding permission "scripting" in manifest
"permissions": [
"storage",
"tabs",
"activeTab",
"scripting"
]
Once the scripting perimission is provided, we can use the scripting api like below
In background.js,
chrome.tabs.query({}, (tabList) => {
if (!tabList.length) return;
tabList.forEach((tab) => {
chrome.scripting.executeScript(
{
files: ['contentScript.js'],
target: {
tabId: tab.id,
allFrames: true
}
}
);
});
});
In the above code we are executing the contentScript for all the available tabs in tab browser.

Resources