Grab current URL from within extension? - javascript

For my Google Chrome extension, I need to grab the current URL. I know that, in regular JavaScript, I can just use this to get the link and host:
var hostname = window.location.hostname;
var url = window.location.href;
But how can I do that within an extension? I actually got it to work by using this as an example, but it seems a bit overkill for what I want to do. Is there a better way to get the current URL, maybe without injecting a script into the page?

You can use chrome.tabs.query() to get the current URL into a variable inside your extension code:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function(tabs) {
var url = tabs[0].url;
});
Remember: the part of your code that'll use the url variable should be inside the (anonymous) callback function above, not elsewhere. Otherwise, you'll get an undefined value, as Chrome extension code is executed asynchronously.

Related

How to get URLs of page's requests?

I am working on a Chrome app and I need to find one of the request urls (the request is initiated in a JS script).
The page script after loading asks for .../online_mektep/lesson/L_(page id)/index.json and I need this page id. How can I find out the URL?
The only way I can see now is to modify the original script with a web request and just get the data before the request. Are there other ways?
Not sure if I completely understand what you're trying to accomplish, however: maybe you can add a listener and get the url. Then you can split the URL afterwards and get the route parameter you want
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
console.log('onBeforeRequest', details.url);
const yourUrl = details.url // example: ".../online_mektep/lesson/L_(page id)/index.json"
const pathArray = yourUrl.split('/')
console.log(pathArray[3].split('_')[1]) // should output (page id)
},
);

Suggest download filename asynchronously in Chrome Ext

I'm writing my first simple Chrome extension which should organize downloads into subfolders based on the title of the tab they're downloaded from. I'm planning on extending this in future, but for the time being I can't even get this simple functionality to work. The problem seems to be that the 'filename suggest' function cannot be called from within the asynchronous tab query. Code below is the full contents of the background JavaScript file:
chrome.downloads.onDeterminingFilename.addListener(function (item, __suggest) {
//Find active tab
chrome.tabs.query({ active: true }, function (tabs) {
var activeTab = tabs[0];
//Generate filepath
var filepath = activeTab.title + "/" + item.filename;
//TODO: Sanitize filepath.
//Suggest filename for this download.
__suggest({ filename: filepath });
})
});
The error logged by the console is:
suggestCallback may not be called more than once. (extensions::downloads:42)
I've checked that the suggest function (in my JS) is definitely only called once. Any ideas how I can fix/work around this?
As the documentation says:
If the listener calls suggest asynchronously, then it must return true.
So you need to add return true after your call to chrome.tabs.query.

Firefox addon SDK replace request

I tried to replace by a local script the url of scripts loaded by websites.
I tried to channel.redirectTo() with data.url() and chrome:// (with contentaccessible=yes flag in manifest), but doesn't work, so I compared a regex pattern, if true, it will cancel the XHR GET request.
For example
<script src="http://url/to/script.js"></script>
become
<script src="resource://url/to/new/script.js"></script>
or
<script src="chrome://url/to/new/script.js"></script>
Now I need to replace the url or inject my new script to the page
main.js
var listener = function (event) {
var channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
var match = someFunctionToMatchRegex(channel.URI.spec);
if (match) {
channel.cancel(Cr.NS_BINDING_ABORTED);
}
};
events.on("http-on-modify-request", listener);
I have a redirect module here which is a good example for what you want to do. You might be able to use it, though the module only takes specific urls and not reg expressions at the moment. I'd certainly take a pull request to make this change though.
The code basically just uses redirectTo as you mention, so something else is wrong.

Triggering Script VIA URL variable

As of now, on my page, the following html is working fine to trigger the following javascript function :
Link to other section
What I'd like to do is to have the javascript function triggered on page load when a specific variable is added to the URL. (Instead of having it as a link on the page)
For example, if url is www.mysite.com, page loads normally. If URL is www.mysite.com/?variable=1 , the script is triggered and user is redirected.
(I know there are other ways to redirect a user to another page, but I need to use this specific script, since the destination is dynamic from one type of user to another.)
I have very basic javascript knowledge and can't make the code I found here work : Triggering Script VIA URL . What they're doing is triggering a fancybox through URL variable. I believe that it's the same thing I want to achieve here. I'm just not to sure how to modify the code to go from "fancybox" to "redirectToOtherSection()"
var $j = jQuery.noConflict();
$j(document).ready(function() {
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('globe=1') != -1) {
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
}
}); // extra curly bracket removed
$j("a#fancy").fancybox({
'padding': 0,
'overlayShow': false // extra comma removed
});
They are using jquery, not sure if jquery is needed in my case?
Any help is much appreciated!
Thanks
based on what you've said you dont need jquery, try
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('variable=1') != -1) { // where variable 1 is wqhats in you url
redirectToOtherSection();
}

Chrome Extension: How to get current webpage url from background.html

From my knowledge it is not possible directly by getting tab.url (only possible in the popup.html) and doing message passing also requires that popup.html be open. Is there anyway to bypass this and get the current page url from background.html?
My best shot was with message passing, which I used this code in background.html
var bg = chrome.extension.getPopupPage();
var myURL = bg.myURL;
then in popup.html I had:
chrome.tabs.getSelected(null, function(tab) {
var myURL = tab.url;
})
Anyways the above does't work at all. Anybody know of a way to do this without having to actually open up the popup?
chrome.tabs.query is supported from background pages, of course as long as you have the tabs permission. This is the supported route as of Chrome 19.
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
var tab = tabs[0];
var url = tab.url;
});
Note that currentWindow is needed because it would otherwise return the active tab for every window. This should be guaranteed to only return one tab.
Of course, keep in mind that this is an asynchronous API – you can’t access any data it provides except from within the callback function. You can store values (such as url here) at a higher scope so another function can access it, but that will still only provide the correct result after the callback is executed.
(The below is my original answer kept for posterity – this method is no longer necessary, requires an always-running background page, and getSelected() is deprecated.)
First put this in background.html and make the myURL variable global:
var myURL = "about:blank"; // A default url just in case below code doesn't work
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked
chrome.tabs.getSelected(null, function(tab) {
myURL = tab.url;
});
});
Then run this in popup.html when you want to get the page url:
chrome.extension.getBackgroundPage().myURL;
So if I were to make that appear inside the popup and I went to Google and clicked your page or browser action, I'll see http://google.com/webhp in the popup.
Upon seeing this post I felt that there should be a way to mark a discussion as "obsolete".
Reasons being...
This question needs to migrate to manifest v2 and...
The answers both are not working. I am using a select onchange and posting the current tab's url which is not working.
Might be these all worked in manifest v1.
My answer is ...
var myURL = "not set yet";
window.addEventListener('load', function () {
chrome.tabs.getSelected(null,function(tab){
myURL=tab.url;
});
This is a little more work but works like a charm...
I would use a content script; it's relatively simple & allows you to get any info from current page you might want. Have the background page "inject" the script into the current webpage to gather the info you need. The script then just passes it back to the background.
background.js:
// Icon is clicked and triggers content script to be injected into current webpage
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: 'inject.js' });
});
// Listens for message back from content script and then runs
chrome.runtime.onMessage.addListener(function (request) {
var URL = request.url;
});
inject.js (content script):
// Gathers up in the information that you need from webpage
var pageInfo = {
"url": window.location.href
};
// Sends the information back to background.js
chrome.runtime.sendMessage(pageInfo);
Hope this helps someone!
chrome.tabs.getSelected(null, function(tab) {
var myURL = tab.url;
});
I don not understand, the code above can be used in background page to get the current tab's url.

Categories