chrome.tabs.executeScript not working? - google-chrome-extension

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.

Related

Chrome extension: How to inject HTML into any tab w/o using <all_urls>

I am trying to inject a content script to the current tab of the user once the timer is done. Thus, my manifest is:
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["jquery-3.5.1.min.js", "flipclock-min.js", "content.js"],
"css": ["normalize.min.css", "styles2.css", "flipclock.css", "css.css"]
}]
According to web store publishing process:
Broad Host Permissions
Instead of requesting broad host permissions, consider using the
activeTab permission, or specify the sites that your extension needs
access to. Both options are more secure than allowing full access to
an indeterminate number of sites, and they may help to minimise review
times.
The activeTab permission allows access to a tab in response to an
explicit user gesture.
{
...
"permissions": ["activeTab"]
}
It makes sense for me to use activeTab instead. However, as they mentioned, I can use it in permission not content_scripts or else I would get:
Invalid value for 'content_scripts[0].matches[1]': Missing scheme separator.
How should I go about this?
activeTab won't work on timer fully automatically because it needs an explicit user action: the user must click your extension icon (or interact via a commands API hotkey, a contextMenus API menu, or an omnibox API keyword, more info in the documentation) to start or set the timer.
Through such user action activeTab will grant access to the current tab so your background script can use chrome.tabs.executeScript to inject the scripts (use one call per each script).
And, remove content_scripts in manifest.json.

Extension: Use runtime.sendMessage/port.postMessage with only activeTab permission?

I'm reading about message passing between extension and webpage, and I have a question about permissions.
My use case is: I need to communicate with all webpages, but only the active one. On the webpage, when the user clicks on a button "[Connect with my Extension]", it sends a message to the extension. What I'm doing now, is I'm injecting a content_script inside all the webpages:
// manifest.json snippet
"permissions": ["storage"],
"content_scripts": [{
"js": ["content.js"],
"matches": ["http://*/*", "https://*/*"],
"run_at": "document_start"
}],
and content.js does chrome.runtime.sendMessage/chrome.runtime.onMessage with the background. It works, but when I publish my extension, Chrome says:
Because of the following issue, your extension may require an in-depth review:
Broad host permissions
Instead of requesting broad host permissions, consider using the
activeTab permission, or specify the sites that your extension needs
access to. Both options are more secure than allowing full access to
an indeterminate number of sites, and they may help minimize review
times.
The activeTab permission allows access to a tab in response to an
explicit user gesture.
{ ... "permissions": ["activeTab"] }
My question is: is there a way to achieve what I want by using activeTab only, as Chrome suggests?
My initial understanding is that NO. activeTab is only activated on some specific user interactions, whereas I would need to activate it on button click inside the webpage. So my only hope is to battle with Chrome's "in-depth reviews". Is that right?
Thanks.

Using tabs.executeScript in iframe

I'm trying to implement an extension that can auto fill all fields in an application website. Currently it works great in main frame, but doesn't work if the fields are in a iframe.
I'm allowing users to either use content script to auto inject JS or click a button to inject JS manually.
The problem I have is my JS is not injecting into iframe even I set allFrames to true, but content script work.
"content_scripts" : [
{
"matches" : ["https://*/my_url/*"],
"js" : ["/auto_fill.js"],
"all_frames": true
}
]
This content scripts work fine, JS is being injected. However,
my_button.addEventListener('click', () => {
chrome.tabs.executeScript(null, {
file : "/auto_fill.js",
allFrames : true
})
});
This executeScript doesn't work, nothing happen.
The iframe I'm trying to work with is kinda a dynamic iframe (where I have to click few buttons to load and navigate to the application site I want)
Do I have to find out the iframe id or tab id in order for this to work, please provide some hints.
Please let me know if I'm not making myself clear.
Thank you so much for your time.
As the comments revealed, the extension is using the activeTab permission without host URL patterns (just as the documentation suggests), but this permission only grants access to the tab's main URL. When an iframe points to a different URL origin, it won't be granted by activeTab, which is an intentional restriction enforced since Chrome 45, see https://crbug.com/826433.

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);
});

User configurable url permissions in chrome extension

I am creating a chrome extension that adds an action with a global hotkey to JIRA. I can hard code the url for my own instance of JIRA into my extension, but I would like this url to be user configurable as other users will have different urls for their own JIRA instances.
I would like to know if there is a better way of doing this than just giving my extension permission for all urls and checking in my background script to compare the current url to the one the user has chosen as a setting. Ideally my background/inject script would only run on the users chosen url. I looked at the permissions api but can't figure it out.
My current manifest.json looks as follows, I have hard coded permission to my jira url, is there a way to make this permission user configurable?
{
"permissions": [
"contentSettings",
"storage",
"commands",
"http://myjiraurl/*"
],
"background": {
"matches": [
"http://myjiraurl/*"
],
"scripts": ["src/background/background.js"]
},
"content_scripts": [
{
"matches": [
"http://myjiraurl/*"
],
"js": [
"js/jquery.min.js",
"src/inject/inject.js"
]
}
]
}
Whatever you do, in order to inject into arbitrary hosts, you have to have http://*/ and https://*/ in your permissions, preferably optional permissions. Your proposal - comparing the current url with the one in the settings - sounds very reasonable: Just compare the current url with the one in the setting and make a chrome.permissions.request if it matches, silently stop running your code if it fails.
I can think of one work-around to avoid that, but honestly it's not giving you much:
Use http://*/ and https://*/ as optional permissions (you should really really make them optional anyway).
Make the chrome.permissions.request call at the time the user is modifying the options.
In your background script, make a chrome.permissions.contains call for the current url and silently stop running your code if there's no permission.
The result of the above is that instead of comparing the current url to the one in the setting, it will compare the current url with whatever the extension has previously got permission for. I guess it simplifies the background script a bit (you don't have to get the url stored in the settings), but makes the options page code a bit more complicated.

Resources