I have a simple Chrome extension that adds a browser action. When the extension's popup is opened, it needs to access the current tab's URL. Since it doesn't need access to all the tabs, I just have the
activeTab
permission specified in the manifest:In theory, that should give the popup access to the active tab's URL, but the URL is not returned when I query the tabs from within a
require()
call in the popup's main.js
file:The console shows
undefined
for the URL. However, if I make the same call from a plain .js file that doesn't use require()
, it works fine:That displays the correct URL, and I can access that global
tabURL
inside the require()
call just fine. When I right-click the browser button and inspect the popup, the console output looks like this:Even stranger is that I've sometimes seen the URL available from within that call to
chrome.tabs.query()
inside the require()
call. But mostly it doesn't work. Something about how RequireJS loads scripts seems to confuse Chrome and take away the URL access for the loaded script. This is in Chrome 40 on Windows. Obviously, the workaround is to grab the URL in a separate script and store it in a variable, but that feels a bit kludgy. I'd like to see if there's a proper way of getting this to work with RequireJS.
The full plugin source is here if anyone wants to test it on their machine: https://github.com/fwextensions/requirejs-url-test
Edit
As Rob W. explains below, this actually has nothing to do with RequireJS. The only reason that the code in my
get-url.js
file above returned the correct URL was that it happened to run before the devtools window opened. If I change that file to this:Then it runs after the devtools window is open and fails as well. RequireJS isn't the culprit.
jdunning
jdunningjdunning34211 gold badge22 silver badges1515 bronze badges
2 Answers
You don't see a URL because you've only set the
activeTab
permission (not the tabs
) permission AND the last focused window is the developer tools (for which you don't have activeTab
access) (and since Chrome 41, devtools tabs/windows are invisible to extensions, so tabs
will be an empty array).The good news is that this problem is specific to the devtools window being opened for your extension page, so the issue only occurs during development and not during actual use by users.
Extension popups are associated with a window, so you can use
Rob WRob Wchrome.tabs.query
with currentWindow:true
to get the correct answer:279k5454 gold badges657657 silver badges588588 bronze badges
To overcome the devTools bug that Rob W. reported in his post, the following
jakejakegetActiveTab
workaround seems to consistently work for me (even when there are multiple devTools windows open). It works by always saving a reference to the activeTabId
in the background page, whenever the tabs.onActivated
event fires.1,01322 gold badges1717 silver badges2929 bronze badges
Chrome Extension Get Url Of Current Tables
Not the answer you're looking for? Browse other questions tagged javascriptgoogle-chromegoogle-chrome-extensionrequirejs or ask your own question.
I'm writing a Chrome extension and, in one part of it, I need to get the current tab's title and URL when a button on the popup page is clicked.
I've worked with Chrome's message passing system before and, after much effort, managed to get it to work, on many occasions. However, I've never had to use them with popup pages and, from what I've read, it's much more difficult to do.
The timeline I've managed to figure out so far is this:
popup.html
/popup.js
: Button is clickedpopup.html
/popup.js
: Request / message is sent to the content scriptcontentScript.js
: Request / message is received from the popup pagecontentScript.js
: The title and URL of the current tab are stored in a variablecontentScript.js
: The 2 variables are sent as a stringified responsepopup.html
/popup.js
: The 2 variables are parsed from the response
Usually I'd be able to figure this out but, I've read a few things that have thrown a spanner in the works, such as:
chrome.tabs.getSelected
can only be used in a background page / script. Does this mean that content scripts don't need to be used at all?- Messages cannot be sent directly from the content script to the popup page, they have to go via a background page
- A popup window has to be confirmed as existing before a message can be passed to it (although, I think I know how to do this)
I already found Chrome's message passing system difficult enough but, this has totally confused me. Hence, this post.
mythofechelonmythofechelon2,00088 gold badges3030 silver badges3939 bronze badges
2 Answers
chrome.tabs.getSelected
is deprecated. You should use chrome.tabs.query
instead.chrome.tabs.query
requires two parameters: a query object and a callback function that takes the array of resulting tabs as a parameter.You can get the 'current tab' by querying for all tabs which are currently active and are in the current window.
Since the query will return a Tab array containing the current tab alone, be sure to take the first element in the callback
Et voilà:
fnyfny17.6k88 gold badges7070 silver badges103103 bronze badges
Never mind.
Turns out, you can actually use
mythofechelonmythofechelonchrome.tabs.getSelected
directly from the popup window. Someone lied. ¬¬2,00088 gold badges3030 silver badges3939 bronze badges
Not the answer you're looking for? Browse other questions tagged javascriptgoogle-chromemessage or ask your own question.
Get a
tabs.Tab
containing information about the tab that this script is running in.You can call this function in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.
This is an asynchronous function that returns a
Promise
.Syntax
Parameters
None.
Return value
A
Promise
that will be fulfilled with a tabs.Tab
object containing information about the current tab. If any error occurs the promise will be rejected with an error message.Examples
Get information about the current tab:
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHubDesktop | Mobile | ||||
---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Firefox for Android | |
getCurrent | ChromeFull support Yes | EdgeFull support 14 | FirefoxFull support 45 | OperaFull support Yes | Firefox AndroidFull support 54 |
Legend
- Full support
- Full support
This API is based on Chromium's
chrome.tabs
API. This documentation is derived from tabs.json
in the Chromium code.Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.
Bare minimum Chrome extension to inject a JS file into the given page when you click on the browser action icon. The script then inserts a new div into the DOM.
background.js
// this is the background code.. |
// listen for our browerAction to be clicked |
chrome.browserAction.onClicked.addListener(function (tab) { |
// for the current tab, inject the 'inject.js' file & execute it |
chrome.tabs.executeScript(tab.ib, { |
file:'inject.js' |
}); |
}); |
inject.js
// this is the code which will be injected into a given page.. |
(function() { |
// just place a div at top right |
var div =document.createElement('div'); |
div.style.position='fixed'; |
div.style.top=0; |
div.style.right=0; |
div.textContent='Injected!'; |
document.body.appendChild(div); |
alert('inserted self.. giggity'); |
})(); |
manifest.json
{ |
'name': 'Injecta', |
'version': '0.0.1', |
'manifest_version': 2, |
'description': 'Injecting stuff', |
'homepage_url': 'http://danharper.me', |
'background': { |
'scripts': [ |
'background.js' |
], |
'persistent': true |
}, |
'browser_action': { |
'default_title': 'Inject!' |
}, |
'permissions': [ |
'https://*/*', |
'http://*/*', |
'tabs' |
] |
} |
commented Apr 20, 2016
You're a hero, Dan Harper! |
commented Sep 14, 2016
AMAZING |
commented Sep 27, 2016
Even better, this works with: .. avoiding the dreaded 'this script can read and change all your data on the websites you visit'. |
commented Sep 28, 2016
thanks for this! is it easy to make this work on specific urls without clicking the extension? great work! |
commented Oct 13, 2016
@Thatkookooguy yes. I'll leave this here in case anyone needs a heavier template. http://extensionizr.com/ |
commented Oct 15, 2016
thanks for this. I have a problem. I want to take info at website. I changed this application. background.js chrome.browserAction.onClicked.addListener(function (tab) { // for the current tab, inject the 'inject.js' file & execute it chrome.tabs.executeScript(tab.ib, {file: 'inject.js'}, function(result) { console.log(result[0]) } ); }); inject.js Function writes t3 on console. but don't return t3 variable. console.log(result[0]) writes 'null' ; what is the problem this code ? thaks good job |
commented Oct 28, 2016
Can I inject css any the same way? |
commented Feb 7, 2017
background.js chrome.tabs.executeScript(tab.ib, { Shouldn't be there: chrome.tabs.executeScript(tab.id, { tab.id instead of tab.ib ? In this case tab.ib is null, so:
|
commented Jun 24, 2017
This is amazing |
commented Jul 9, 2017 • edited
edited
commented Aug 16, 2017
This does not work.. |
commented Aug 26, 2017
Great job!! |
commented Oct 23, 2017 • edited
edited
Great job !! can we execute jquery with this ? what changes i need to add to execute jquery script |
commented Oct 29, 2017
super and amazing............. |
commented Dec 1, 2017
Man, you saved my day. Thanks! |
commented Jan 1, 2018
is there a way to run/execute a Chrome Extension in a new tab/window by loading the extension's code in that new tab or window? https://stackoverflow.com/questions/48048617/load-run-execute-chrome-extension-in-new-tab |
commented Jan 3, 2018
I wish I could kiss you :') |
commented May 2, 2018
Never before this even tried a Chrome Extension. Found this, check how to load on chrome. in less than 30 seconds all working. A real hero Darper! |
commented Jun 7, 2018
THANK YOU! |
commented Jun 18, 2018
I want to insert bypass frame busting code into html. I donot know how to insert whole script. <script type='text/javascript'> var prevent_bust = 0; window.onbeforeunload = function() { prevent_bust++; } setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2; window.top.location = 'http://www.example.com/'; } }, 1); prevent_bust = 0; window.onbeforeunload = function() { prevent_bust++; } setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2; window.top.location = 'frame_busted_page.html'; } }, 1); </script>Thank you . |
commented Jul 31, 2018
Danharper thanks for the idiomatic kit for getting things going. Danvine thanks for the heavier template. Looks great and will try that. I plunged into extension stuff, as I was getting tired of High Contrast Chrome extension not working, or only working sporadically. Not sure why or what in my environment is making it not work. But I need something like that badly. If you have any tips on how to make gmail display all its views/texts white on black background it would be a great head start for me. That would be good for the start to be extended other pages as well. Thanks in advance. |
commented Jul 31, 2018
@dipongkor You can inject CSS with the insertCSS method. Though beware, you may experience some priority issues doing it this way. For some use cases the previous is enough. For others my recommendation is to inject a script that injects the css that you need. |
commented Nov 28, 2018
Hey, I'm a java noob and i'm trying to inject a script onto a live page. If anyone here can help me out just a little that would be great! PM me at twokeywood -skype or [email protected] |
commented Dec 10, 2018
This is truly so Convenient. Cheers and Thanks man! |
commented Feb 19, 2019
2d fighter maker enterbrain download. How do I click on a JavaScript pop-up on the page, that does not have an element ID |
commented Feb 23, 2019
Lifesavveerrrrrr |
commented Mar 11, 2019
is there a way to insert a linked JS file? e.g. insert the file at this URL: testsite.com/files/script.js |
commented Mar 26, 2019 • edited
edited
commented Apr 14, 2019 • edited
edited
@brettsprad Yes you can. Just create a new script element, add it to the document and then set the src to your url Something like this: |
commented May 28, 2019
<3<3 |
commented Jun 26, 2019
This is a newbie question: When I hear 'Chrome Extension', I think of code that the user has to agree to run, and that can be removed by the user at any time. Is this like that, or is 'extension' an overloaded word in this context, and means something else? Thanks! |
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment