Simplest Way to get the current Tab Id? - javascript

I dont really unterstand how the Chrome Extension API works. It was a rough to understand how the background.js and the content.js works, but my current Problem is, that the function insertCSS(); seems to need the tabId, even if the official documentation says that its optional.
So, none of the Answers on this plattform could help me, because I dont even understand the Concept of the whole API.
So can anybody explain me, why something like this is not possible?
var tabInfo = chrome.tabs.getCurrentTab();
var id = tabInfo.tabId;

There are several questions to be answered here.
Literal question
So can anybody explain me, why something like this is not possible?
var tabInfo = chrome.tabs.getCurrentTab();
Short answer: because most of the Chrome API does not return a value; it is asynchronous, meaning that some other component of Chrome will work on getting the answer while JS execution resumes.
A comprehensive overview of JS asynchronicity can be read at this canonical question.
There are two ways to deal with it:
Use callbacks, and be aware that the actual callback execution happens after the rest of the calling code.
Use async/await and/or Promises. The WebExtension polyfill can help with that, but it's outside the scope of the question.
Question in title
Simplest Way to get the current Tab Id?
or "why chrome.tabs.getCurrentTab won't help you".
chrome.tabs.getCurrentTab() returns the tab ID of the calling page. See the docs.
This is of limited utility: only extension pages (and not content scripts) can call this API.
Extension pages are:
background (no tab ID),
popup (no tab ID),
options page (it's complicated as it's embedded in a Chrome page),
"other" extension pages opened in a visible tab (here, it works as expected).
It's not your use case, as established in the comments.
The actual way to get the current active tab is chrome.tabs.query() with the query {active: true, currentWindow: true}, but keep on reading.
Actual question you're having
As reconstructed from the comments, here's the actual scenario you're having:
I have an event in a content script. I need to call the tabs.insertCSS API, so I'm messaging the background page to do it for me. How do I get the tabId for this call?
Well, the key here is to take a closer look at the runtime.onMessage event listener signature:
The callback parameter should be a function that looks like this:
function(any message, MessageSender sender, function sendResponse) {...};
What's a MessageSender?
An object containing information about the script context that sent a message or request.
tabs.Tab (optional) tab
The tabs.Tab which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app.
[...]
Jackpot. We're sending the message from a content script, and the listener is handed the sender.tab information "for free". We just need a quick detour into tabs API docs to see what a Tab contains, and we have it:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
chrome.tabs.insertCSS(sender.tab.id, {/*...*/});
});
Misconception
my current Problem is, that the function insertCSS() seems to need the tabId, even if the official documentation says that its optional
It doesn't. If you call it omitting the tabId, which makes the details object the first argument, then Chrome will assume you want the "the active tab of the current window".
It may seem that this doesn't work if you're trying to execute it in the Dev Tools window for the background page. That's because in this instance there's no such tab. The current window is the one you're putting the console command in. So what the call does without the tabId is very sensitive to what actually is the current window.
It may also be the case that you don't have the permissions to inject in the current active tab, that would also fail.
Generally, it pays to be specific with the tab ID, it removes uncertainty about the logic of the extension.

Related

Javascript: How can I check to see if url to fire exists before firing it?

I am getting urls from a feed that I assign to list of buttons, some of the urls produce 404s when clicked on said buttons. Is there a way to check if the landing page exists first before I fire it?
Some of these urls have tracking pixels in them to know when they are clicked so I wouldn't want to fire it in an iframe or a similar solution as it would possibly track twice to test if it exist first before it fires.
Is this even possible? The domains will not be the same and I can't use jQuery.
To test an url you must access it. So, without an external service, you can't test them beforehand.
W3C provides a link checker: https://validator.w3.org/checklink
"The program can be used either as a command line tool or as a CGI script."
Maybe you can use it to test an url and, after, create or not your button.
I don't know if there is a limit for this service, so check the documentation!
http://search.cpan.org/dist/W3C-LinkChecker/bin/checklink.pod

Anyway to change the "Name", or "Initiator", or add new tabs in Chrome Dev Tool's Network view?

I was wondering if there was anyway to change the name or initiator columns in the Network Tab in Chrome's Dev Tools.
The issue is that, currently I'm making a web app, and it makes tons of POST calls using jQuery. that's all fine and dandy, however, when I have 10+ calls, obviously the Network tab gets flooded with POST calls.
All calls are to the same PHP script, thus the Name column is all the same. Also, since I'm using jQuery, the initiator is set to jQuery. I was wondering if there was any way to customize this view so that I know what script is calling the POST without having to open each call and see it's properties.
It'd even be nice to see maybe a truncated version of values sent right in the list view. This way I can just look at each call and know exactly what function or script called it, or at least have a better idea, rather than 10+ entries of Name: " xxx.php".
You can add custom columns that show you the values of response headers by right clicking on the table header and selecting Response Headers > Manage Header Columns:
You can also hide columns via this right-click menu.
You can also add a query to the url you are posting to, with information about what function you are calling.
Example:
If you are posting to https://myserver.com/api it is the last part api that will be displayed as the name in the network tab.
So you can extend that url with https://myserver.com/api?whatever and you will see that in the network tab name. The back end server can and will just ignore that extra query in the url.

Chrome extension: Get current tab from popup

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 clicked
popup.html / popup.js: Request / message is sent to the content script
contentScript.js: Request / message is received from the popup page
contentScript.js: The title and URL of the current tab are stored in a variable
contentScript.js: The 2 variables are sent as a stringified response
popup.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.
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.
var query = { active: true, currentWindow: true };
Since the query will return a Tab array containing the current tab alone, be sure to take the first element in the callback
function callback(tabs) {
var currentTab = tabs[0]; // there will be only one in this array
console.log(currentTab); // also has properties like currentTab.id
}
Et voilĂ :
chrome.tabs.query(query, callback);
Another way is to send a message from the popup to the content script which then returns the URL window.location.href

"Undefined" appearing sometimes in the URL of my ASP.NET application (somehow google related?)

Some users repeatedly run into a very mysterious problem when using my web application.
In the middle of using it, they'll click a button or link that takes them to another page, but there will be a "page not found" error, because the URL is something like:
http://www.correctwebsitename.com/undefined
I thought it might be a javascript bug in my app: a redirect done by choosing a page name (maybe with some parameters) where one of the values is bad, resulting in the page name = "undefined". But there is no such code in my app anywhere, and this happens on many different pages, seemingly at random.
The one thing that seems to make it happen more often is if the user logged in originally by clicking a link in an email message in gmail. But a user who cut and pasted the link URL into a browser window said it still happened. Googling around reveals some hints that some kind of Google redirecting or caching is happening behind the scenes.
Any ideas?
Edit:
I'm not getting responses from anyone familiar with how gmail links etc work, does anyone know what SO tags google experts "hang around in"?
Edit 2:
Awarding bounty to top answer for useful info and temporary workaround idea, but still interested in real solution to the problem, so not accepting workaround as solution.
I believe you are right about gmail doing something with the links. See the gmail image below:
Non-standard header fields are conventionally marked by prefixing the field name with X-
Its probably behaving like... oh well, Google, and inspecting everything.
To stop google search from tracking my clicks i had to create a userscript to rewrite one of their functions:
rwt = function(){};
Maybe you can try something similar for gmail.
What is rwt?
rwt() is a javascript function from google search that rewrites the links to track which site you have visited.
for example, searching for "greasemonkey" showed the mozilla addons page as the first result. clicking on it opened
https://www.google.com.br/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CCUQFjAA&url=https%3A%2F%2Faddons.mozilla.org%2Fpt-BR%2Ffirefox%2Faddon%2Fgreasemonkey%2F&ei=iWNtUIXjIoyQ8wTxv4DQAQ&usg=AFQjCNEO9EJcHp9rAmKyD_XZF2Bt6hs_YQ&sig2=P19xVUsD-Q1G_9AiUBP3PQ
and then redirected to
https://addons.mozilla.org/pt-BR/firefox/addon/greasemonkey/
The image above and the rwt() case is just to show you that there is a great chance that gmail is changing the links, so this could be related to your problem.
Since there is nothing you can do at gmail's side, maybe you could fix it on your server, by redirecting http://www.correctwebsitename.com/undefined to http://www.correctwebsitename.com or any other page that you'd like your users to see.
So, be it from gmail or any other referer, every time a client lands on http://www.correctwebsitename.com/undefined redirect him to another page.
so maybe I can figure out how to just send them back to the page they
came from
ASP
if not request.UrlReferrer is nothing then
response.redirect (request.UrlReferrer.tostring)
end if
JS (for this to work, you would have to actually create a page called undefined)
if (window.location.href.toLowerCase().indexOf('undefined') > -1) {
// this works
window.location.href = document.referrer;
// this works too (uncomment to enable)
// history.back();
}
remember that if the user directly typed the url or used the link from favorites there wont be no referrer
I would suggest you to check the below things in your application.
Is there any code in your application, apart from what you own ?
there can be injected code by third party applications, like for ex "AddThis" adds an extra #parameter to your url sometimes, in your case its clear that a javascript is trying to playaround with the location.href as "undefined" is something which many js developers will come across.
by adding an # will help do cross site communication, some bug might also be causing an issue here.
Do a complete search in your code for "location.href" and see if you have used it anywhere.
Sometimes third party addons on the browser too might cause this issue
hope these would help you narrow down to your problem.
if you are not able to trace out the issue anywhere, i would suggest you to override 404 functionality on your webserver and implement the solution using Referrer.

message passing in a Google chrome extension

There are a few questions about this but none met my needs. I have created an extension and I am trying to communicate between a content script and my options.html. I have been trying to use the chrome.extension.onRequest.addListener and the chrome.extension.sendRequest and neither work at all. No commands are executed or anything. Here is my code:
content script:
chrome.extension.sendRequest({command:value}, function(response) {});
options.html
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
alert("in onRequest request.command = " + request.command);
decide_command(trim(request.value));
sendResponse({});
});
none of the alerts are executed and none of the functions are executed. I even tried using the example in the messaging API page and it didn't trigger any alerts or anything. I have tried a bunch of different combinations like putting the extension ID in the sendRequest to make sure its going to the right place, I have excluded the sendResponse to make sure it wasn't ending too quick. I have debug alerts all over and none get triggered except for the ones before and after the send request command in my content script. So I would assume it either gets executed and fails or something like that. Any help would be greatly appreciated I have been working on this for days.
I believe Chris noted an issue already: an extension's option page isn't running all the time, and is therefore not available to receive or generate messages. Background pages are better for this sort of communication, as they're always running, always available, and therefore always capable of responding to messages.
I'd suggest reworking your extension's architecture a bit such that the content script gathers relevant information and sends it to the background page. When the options page is opened, it can request the state from the background page. The background page is then responsible for maintaining state in a reasonable way, and for pushing information back and forth between the other pieces of your extension.
Does that make sense?

Categories