After doing some research, the code that I have come up with is this:
var outUrl;
// first get the windowid
chrome.windows.getCurrent(function(window) {
// then get the current active tab in that window
chrome.tabs.query({
active: true,
windowId: window.id
}, function (tabs) {
var tab = tabs[0];
document.write(tab.url)
});
});
This is in a javascript file which is called from my popup html file. It does not, however display the URL of the current website, instead it displays nothing.
I have found multiple posts about this on this and other websites but I haven't been able to implement any of the supposed solutions.
Any help would be greatly appreciated.
Maybe this is what your looking for....
chrome.tabs.query({'active': true, 'windowId': chrome.windows.WINDOW_ID_CURRENT},
function(tabs){
alert(tabs[0].url);
}
);
And the tabs permission needs to be set in the manifest...
manifest.json
"permissions": [
"tabs"
]
I had the same issue. I wrote this extension to display the current URL user is browsing now in the popup.
manifest.js
"permissions": [
"tabs"
]
popup.js
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
callback(url);
});
}
function renderURL(statusText) {
document.getElementById('status').textContent = statusText;
}
document.addEventListener('DOMContentLoaded', function() {
getCurrentTabUrl(function(url) {
renderURL(url);
});
});
Solution:
Get the URL of currently selected tab for Chrome Extension
This code is to get parts of URL, because in tabs[0].url we cannot get parts of URL like host, hostname, origin, port, etc...
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
let link = document.createElement('a');
link.href = tabs[0].url;
})
Further using basic js to get its part:
link.host = "password remember.web.app"
You can use other like link.hostname, link.hash, link.host, link.href, link.origin, .link.pathname, link.protocol, link.search
Hope it solves your problem!
Related
I am using execute script, but it only works when a user clicks on the icon. How can I make it so that it runs when the user moves to a new page like a content script?
I tried calling the function within the page but that also does not work.
const page = () => {
alert("popup");
}
function test(){
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: page
});
});
}
test()//does not work
Solved
I had the wrong source unpacked files added...
With the script below i get the error:
Uncaught (in promise) Error: Cannot access contents of url "https://www.reddit.com/". Extension manifest must request permission to access this host.
Script:
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
args: [VerCodeComplete],
func: (VerCodeComplete) => {
document.getElementById("subject").value = VerCodeComplete;
document.getElementById("text").value = VerCodeComplete;
},
});
});
I have used chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { in other locations within the .js without issues.
The way I understand this, the script is not trying to run in the correct window and tab.
If I only have one Chrome window open this works as expected, with more than one window, the error above appears.
Is there something obvious I missed?
Permissions from manifest:
"permissions": ["tabs" , "scripting" , "activeTab"],
These functions work as expected
//Change the language in KS from EN to NO
$("#Change_btn").click(function () {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
url = tabs[0].url.replace("en-US", "nb-NO");
chrome.tabs.update({ url });
});
});
//Change the language in KS from NO to EN
$("#Change_btn_en").click(function () {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
url = tabs[0].url.replace("nb-NO", "en-US");
chrome.tabs.update({ url });
});
});
The following does not work as expected
//Generate Email code Code_email_btn_en
function Code_email_en() {
const generateRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
};
var VerCodeEN = generateRandomNumber(111111, 999999);
var VerCodeText = "Verification code: ";
var VerCodeComplete = VerCodeText + VerCodeEN;
//Auto-paste to Email
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
args: [VerCodeComplete],
func: (VerCodeComplete) => {
document.getElementById("subject").value = VerCodeComplete;
document.getElementById("text").value = VerCodeComplete;
},
});
});
}
These are all in the same .js file, and functions are called from main .html document.
Language change script changes the URL as expected in the currently active window and tab.
The code generator works as long as there is only one Chrome window. With multiple chrome windows it does not call the actually active tab and window.
Cannot access contents of url "https://www.reddit.com/". Extension manifest must request permission to access this host.
So you need to add the url where you execute the script in your permission array in the manifest
permission: ["https://*", ...]
I have a chrome extension and on start, I open a new tab. This will be my "work" tab.
How to navigate to a new url in this tab?
How to identify this tab and tell him to navigate to the new url?
I'm trying with this code:
chrome.tabs.query( { active: true, currentWindow: true }, function( tabs ) {
chrome.tabs.update( tabs[0].id, { url: "http://stackoverflow.com//" } );
});
but this navigates the current tab to the new url. I need to navigate in my "work" tab.
I think I will need to take an id from the tab that I created on start and use this id as a destination for the later navigates.
but, how to do this?
fixed.
when create the tab, use:
chrome.tabs.create({index: 0, url: 'http://stackoverflow.com'}, function() {});
for update the url in this tab:
chrome.tabs.query( { active: false, currentWindow: true }, function( tabs ) {
chrome.tabs.update( tabs[0].id, { url: "http://stackoverflow.com//" } );
});
active must be set to false.
I am looking to open up a new incognito window in chrome with two tabs. I have:
chrome.tabs.query({
'active': true,
'windowId': chrome.windows.WINDOW_ID_CURRENT
},
function(tabs) {
var url = tabs[0].url;
chrome.windows.create({"url": url,
"incognito": true});
}
);
But I am not sure on how to add a chrome.tabs to open google.com in a new tab in the same incognito tab.
Is that possible?
Also, I cannot gain focus on an incognito window. I can gain the focus when I leave off 'incgonito': true but not when I add it like so:
chrome.tabs.query({
'active': true,
'windowId': chrome.windows.WINDOW_ID_CURRENT
},
function(tabs) {
var url = tabs[0].url;
var urlIntent = "http://google.com";
chrome.windows.create({
"url": url,
focused: true,
"incognito": true
},
function(window){
chrome.windows.update(
window.id,
{focused: true})
});
}
);
In manifest.json you need to add:
"incognito":"split",
As shown here https://developer.chrome.com/extensions/manifest/incognito
I'm creating my first Chrome extension and I need some help. I I think everything is working except the fact that I can't get the current URL of the tab.
var menu = chrome.contextMenus.create({
"title": "extension",
"contexts": ["all"]
});
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var siteUrl = tabs[0].url;
});
chrome.contextMenus.onClicked.addListener(function(activeTab)
{
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var siteUrl = tabs[0].url;
});
var finalUrl = "http://example.com/";
finalUrl += encodeURI(siteUrl);
// Open the page up.
chrome.tabs.create(
{
"url" : finalUrl
}
);
});
Can anyone please help me? Thanks.
EDIT:
Thank you for your replies. I got it working by moving
var finalUrl = "http://example.com/";
finalUrl += encodeURI(siteUrl);
// Open the page up.
chrome.tabs.create(
{
"url" : finalUrl
}
Inside
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var siteUrl = tabs[0].url;
});
chrome.tabs.getCurrent(function(tab){
alert(tab.url);
});
OR if you're in a content script,
alert(document.location.href);
The info you require are provided to you already in the callback of the onClicked listener.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
// The URL of the tab (if any)
var tabURL = tab && tab.url;
// The URL of the page (if the menu wasn't triggered in a frame)
var pageURL = info.pageUrl;
// The URL of the frame (if the menu was triggered in a frame)
var frameURL = info.frameUrl;
E.g. you could achieve what you want like this:
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"permissions": ["contextMenus"]
}
background.js:
var baseURL = 'http://example.com/';
chrome.contextMenus.create({
id: 'myMenu', // <-- event-pages require an ID
title: 'Do cool stuff',
contexts: ['all']
}, function () {
/* It is always a good idea to look for errors */
if (chrome.runtime.lastError) {
alert('ERROR: ' + chrome.runtime.lastError.message);
}
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
/* Check which context-menu was triggered */
if (info.menuItemId === 'myMenu') {
/* Get the URL of the frame or (if none) the page */
var currentURL = info.frameUrl || info.pageUrl;
/* Open a new tab */
chrome.tabs.create({
url: baseURL + encodeURI(currentURL)
});
}
});
If you are using content script you can use
document.location.href
document.location is Object and can provide set of useful chunks in the URL
document.location.host returns domain name ex: "http://www.google.com/"
document.location.path returns the part after the domain name
document.location.hash returns whatever after # symbol in the url
Function:
function getCurrentUrl(callBackFuntion){
//you are in content scripts
if(null == chrome.tabs || null == chrome.tabs.query){
callBackFuntion(document.location.href);
}else{
//you are in popup
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
callBackFuntion(tab.url);
});
}
}
Function call:
function alertUrl(url){
console.log("currentUrl : " + url);
}
getCurrentUrl(alertUrl);