Obtain URL's of chrome popups - javascript

I have written a piece of code which alerts the tab URL after every 2 seconds. However, I am unable to do this for pop-ups. Whenever I open a pop-up; the tab url is of the background page and not the pop-up.
How can i get the url of the pop-up in crome?
<script>
var seconds = 2*1000;
setInterval(function(){
chrome.tabs.getSelected(null, function(tab) {
tabId = tab.id;
tabUrl = tab.url;
alert(tabUrl);
});
},seconds);
</script>
</head>

When you pass null instead of windowId to chrome.tabs.getSelected(), it defaults to "current" window, which is not necessary the selected one, as explained here:
The current window is the window that contains the code that is currently executing. It's important to realize that this can be different from the topmost or focused window.
So you need to find the focused window first, and then get its selected tab:
var seconds = 2*1000;
setInterval(function(){
chrome.windows.getLastFocused(function(window) {
chrome.tabs.getSelected(window.id, function(tab) {
tabId = tab.id;
tabUrl = tab.url;
alert(tabUrl);
});
});
},seconds);

In content_script.js or popup.html:
function get_urlInfo() {
var d = {
'action' : 'getUrl'
};
chrome.extension.sendRequest(d, function(response) {
alert(response.url);
});
};
In background.html:
function onRequest(request, sender, sendResponse) {
if (request.action == 'getUrl') {
sendResponse({'url' : sender.tab.url});
}
};
chrome.extension.onRequest.addListener(onRequest);
It should work!

Related

Chrome Extension: Get current webpage url from background.html not stable

Try to get url in background.html through background.js in Chrome extension.
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;
});
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
logUrl();
})
function logUrl() {
...
eventProperties.setProperty('URI', myURL);
...
}
myURL sometimes shows as "about:blank", it shows actual url after reloading the page.
How shall I fix this?

Refresh after a timer of 5000 seconds and print the alert

I am making a chrome extension to keep refreshing a page unless stop button is chosen. But i am able to do it only once. Here is my code for background.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.type) {
case "table-row-count_start":
alert("Refershing started");
RefreshAndCount();
break;
case "table-row-count_stop":
alert("Stop Refershing");
break;
}
return true;
});
var RefreshAndCount = function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {type: "table-row-count"});
chrome.browserAction.setBadgeText({tabId: tabs[0].id, text: "Counting!"});
});
};
In content.js I did this :
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
alert(message.type);
switch(message.type) {
case "table-row-count":
var x = document.querySelector('table').rows.length;
chrome.storage.sync.set({'value': x}, function() {
console.log('Settings saved');
});
chrome.storage.sync.get(["value"], function(items){
console.log(items);
});
alert("Row count = " + x);
setTimeout(function(){
location.reload();
},100);
break;
}
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
if(key=='value'){
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
}
});
After refresh I want to print the current row count alert everytime. Please help how to do this .
This work fine, for a single refresh but after that I again had to choose the start button from popup.
I want some way that I need not click start button again and the whole process repeats, storing the previous row count in cache or something.
popup.js
window.onload = function() {
document.getElementById("mystartbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_start"
});
}
document.getElementById("mystopbutton").onclick = function() {
chrome.extension.sendMessage({
type: "table-row-count_stop"
});
}
}
Also help me How to keep on refershing that page even if I switch to other tab or minimise my chrome ?
You can use the chrome.storage.local to store data that will be saved over time and over context where you use it. You can set a boolean to true or false to enable or disable autoreload. Then you only have to set it at click on browser action and check it in the content-script to know if you have to reload.
A possible and simple implemtation should be like this : (It depends of the expected behavior)
content.js (have to be injected in the page to autoreload)
var reloadDuration = 5000;
function autoreload()
{
chrome.local.storage.get("autoreload_enabled", function(result)
{
if(result.autoreload_enabled)
{
chrome.runtime.sendMessage({type: "table-row-count"});
window.location.reload();
}
}
}
setTimeout(autoreload, reloadDuration);
This will reload your page every reloadDuration if the boolean set in chrome local storage named autoreload_enabled is true.

Chrome Capturing Visible Tab not working

The code in buttonClicked() function and onTabCreate() function worked when the button is the BrowserAction icon.
But when I added a popup.html and created few buttons in it. When "Trello" button is clicked. I want the code in buttonClicked() to be executed, I put this code in eventPage.js.
The control is reaching the function, but I'm unable to capture the visible Tab now.
Why is it so? How can I fix this?
As evident from the code, imageData is holding the image of the tab (3rd line in buttonClicked())
The last 4th line in buttonClicked(), calls onTabCreate(). InonTabCreate(), I'm passing the imageData, but I'm not receiving the image.
I'll furnish more info if needed.
Thanks
buttonClicked()-
function buttonClicked() {
chrome.tabs.captureVisibleTab(null, {}, function (image) {
imageData = image;
createdTabUrl = chrome.extension.getURL('cardCreate.html');
chrome.tabs.query({ active: true }, function (tabs) {
var i, tab;
// Only select the current active tab, not any background tab or dev tools
for (i = 0; i < tabs.length; i += 1) {
// TODO: more robust way to check if current tab is a page from this extension (either when I get a static extension id or with a flag)
if (tabs[i].url.match(/^http/) || tabs[i].url.match(/^chrome-extension.*\/cardCreate\.html$/)) {
tab = tabs[i];
}
}
chrome.tabs.create({ url: createdTabUrl, index: (tab.index || 0) + 1 }, onTabCreated);
});
});
}
onTabCreate()-
// TODO: more robust way to send image data to page ?
function onTabCreated(tab) {
setTimeout(function (){
chrome.runtime.sendMessage({ imageData: imageData }, function(response) {
// Callback does nothing
});
}, 1000);
var views = chrome.extension.getViews();
for (var i = 0; i < views.length; i++) {
var view = views[i];
// If this view has the right URL and hasn't been used yet...
if (view.location.href == createdTabUrl) {
console.log("----------------------");
// console.log(view);
// console.log(view.location.href);
}
}
}
chrome.browserAction.onClicked.addListener(buttonClicked);
EDIT :
window.onload = function() {
document.getElementById('loginText').addEventListener('click', login);
document.getElementById('Trello').addEventListener('click', buttonClicked);
//listener for ButtonClick
// In popup.html , I included eventPage.js as well.
};

Chrome Extension change div content of a local page

I have a local html page called "PageRedirect.html" for chrome extension that has a p tag with id called "toChange"
I have a function in background.js
function doRedirect(tab,val){
var tabUrl = encodeURIComponent(tab.url);
var tabTitle = encodeURIComponent(tab.title);
// determine the type of redirection
if(val == 1 ){
var redirectURL = chrome.extension.getURL('PageRedirect.html');
}
chrome.tabs.update(tab.id, {url: "redirectURL"});
}
This will successfully redirect the page I want.
However, if I want to dynamically p tag with id="toChange" content from blank to new string that I want.
What can I do in this case?
Is there any demo?
I tried message sending method but it has some problems locating the id.
Something like this
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse)
{
if (request.warning == "true"){
url = request.url;
var elem = document.getElementById("toChange"); // elem will be undefined
}
}
);
I am guessing the reason why it will be undefined is caused by the fact that PageRedirect.js is not the "document".

How to check a "sync" value in an async function?

I try to make some changes on a Chrome extension. I need the extension checks the value and if it is true, then execute a script. If false, then do nothing. I wrote something like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(localStorage["statusOfSomething"]){
chrome.tabs.executeScript(tabId, {file: "file.js" ,runAt:'document_end'});
}
});
But this takes the initial value of localStorage["statusOfSomething"] always. So there is an async function to register a listener for "onUpdated". But I need to check the localStorage["statusOfSomething"] value of "now", not the value of the time by registering the listener.
How can I do this?
Edit:
Actually I was trying to check two things:
if the website is in the site list of extension
if this website is enabled for the extension
Now here the full story;
There are some websites, I defined them on background.js file. Let's say;
a.com, b.com ... etc.
var sites = [{
name : "a",
wildcard : ["*://a.com/*"],
js : "a.js"
},{
name : "b",
wildcard : ["*://b.com/*"],
js : "b.js"
}]
and there are statuses of the sites (enable/ disable; true/false)
I think it was good to store statuses by localStorage, so I write as initial value true:
for(var i = 0; i<sites.length; i++){
localStorage[sites[i].name] =true;
}
As option; it was needed to addListener for changes:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if(request.method == "setSite"){
var name = request.site;
var status = request.active;
localStorage[name] = status;
}
return true;
});
If user checks the checkbox for status option of the website, then options.js sends message:
$('#' + name).change(function(){
var status = $(this).is(':checked');
chrome.extension.sendMessage({method: "setSite", site: this.id, active: status}, function(response) {
console.log(response.data);
});
});
Now, back to background.js , for every update of the tab, I need to check these two things together:
1. am I interested in this website?
2. is it enable for me now?
So I wrote:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete') {
var url = tab.url;
for(var i = 0; i<sites.length; i++){
var site = sites[i];
var name = site.name;
var wildcard = site.wildcard;
if(localStorage[name] && testUrl(url,wildcard)){
chrome.tabs.executeScript(tabId, {file: site['js'] ,runAt:'document_end'});
break;
}
}
}
});
Here, I get the value of localStorage[sitename] true
If you are more interested, you can see the code on github (the version)

Categories

Resources