Google Chrome Extension Running in the background - javascript

I am trying to make a google extension that basically checks the current tab URL to see if the URL is our prefix, so far I have this in my background.html (I have tab and background permissions set in my manifest):
<script type="text/javascript">
chrome.tabs.getSelected(null, function(tab) {
alert(tab.url);
if(tab.url == "http://www.google.com") {
alert("YOU'RE AT GOOGLE");
}
//changeTabURL(tab.url, tab);
});
</script>
So this seems to run only when I first load the extension, it tells me "chrome://extensions" and then it disappears. How do I get it to check each time the user goes to a new URL? Is this possible?
Thanks!

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading"){
//do url check
}
});

use the following:
chrome.tabs.onUpdated.addListener(function(Tab tab) {...});
See the documentation here.

Related

How to add custom alert in Google Chrome Extension?

I'd like to be able to display a styled alert (for example, add image) which the alert dialog is called from the background script of a Chrome Extension (I want to write the code of alert in background.js). Is there any idea how I can display the alert? Is there an APIs Chrome Extension for that?
I have a simple alert without styled :
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab){
if(changeInfo.status == 'complete' && tab.status == 'complete'){
alert("This is a simple alert!");
} });

Reload Chrome DevTools Extension Sidebar on Page Change

This may be a dupe of the question at Google Chrome DevTools Extension - Detect Page Change, but it's been sitting for over a year without a real answer, and maybe my question will provide some new insight into the problem.
I've written a Chrome Extension which inserts a sidebar panel into DevTools. The side panel lists the dataLayer events, a user can click on the desired event and then use the element picker to select another element on the page, and the plugin displays the path between the elements in dot notation.
Here's the link to the Github project: https://github.com/gruebleenagency/gtm-data-layer-sifter
It works as I'd like it to normally, but if you navigate to another page, the sidebar is not initialized again, so it displays the info from the previous page.
You can see that I have this in my background.js file:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
reloadExtension();
}
});
function reloadExtension() {
// ???
}
I'm wondering if there's any way to make the sidebar reload at this point? Or am I going about this in the wrong way? I've spent a lot of time messing around with this trying to get it to work, but nothing seems to do the trick.
Thanks for any and all help.
Here's my solution. It's very possible that this isn't the way it should be done, but I don't have the time to rewrite the whole plugin at the moment, so it'll have to do for now. Any suggestions for how I should have done it would be greatly appreciated. And maybe it will be helpful to someone in a different situation.
Essentially, listen to the tabs.onUpdated event waiting for the 'complete' status, which indicates we've navigated to a new page. Then send message to Devtools.js to refresh the side panel, by setting its page to 'panel.html' again.
In background.js:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
reloadExtension(port);
}
});
function reloadExtension(port) {
var message = {action: "reloadExtension"};
port.postMessage(message);
}
In Devtools.js:
var sb;
createSidebar();
function createSidebar() {
chrome.devtools.panels.elements.createSidebarPane("GTM dataLayer Sifter", function(sidebar) {
sb = sidebar;
sb.setPage("panel.html");
});
}
var port = chrome.extension.connect({
name: "Devtools.js Communication"
});
// Listen to messages from the background page
port.onMessage.addListener(function(message) {
if(message.action == "reloadExtension"){
sb.setPage("panel.html");
}
});
You can do it by listen onNavigated event:
In Devtools.js
chrome.devtools.network.onNavigated.addListener(() => {
console.log('Inspected page reloaded');
});

Send message from popup to content script?

Suppose I want to run a content script when I click a button in the popup page in a google chrome extension?
I have tried the following:
//popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clicked);
main();
});
function clicked(){
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
}
And in the content script:
chrome.extension.onMessage.addListener(
function(message, sender, sendResponse){
console.log("hello world");
}
);
The problem is that the tab in the callback from chrome.tabs.getCurrent( ) is undefined.
Have you given permissions for tabs in manifest.json as shown here.
"permissions": [
"tabs"
],
Moreover tab.id which the following code returns is of popup view (NOT A CONTENT SCRIPT TAB.ID)
chrome.tabs.getCurrent(
function(tab){
console.log(tab);
chrome.tabs.sendMessage(tab.id, "doSomething");
}
);
If you want to send message to tab you are browsing use following code's tab.id, it gives correct results
chrome.tabs.query({"status":"complete","windowId":chrome.windows.WINDOW_ID_CURRENT,"active":true}, function(tabs){
console.log(JSON.stringify(tabs[0]));
console.log(tabs[0].id);
});
Let me know if you need more information
The answer provided by #Sudarshan is valid and works fine, but I just found another solution to my problem. Just thought i put it here:
function clicked() {
chrome.tabs.executeScript(null,
{code:"console.log('hello world');"});
}
It will inject and execute the script.

Javascript, Chrome Extension development, close popup

In my manifest i have this:
"popup": "1_options.html"
and in the above html file I have this code
var saved_email = localStorage['saved_email'];
if (saved_email !== undefined || saved_email != "a#a.com")
{
chrome.tabs.create({url: '0_register.html'});
}
which is working exactly as I want, it opens a new tab with the register.html BUT it still has the popup open on the top right :( (1_options.html)
is there anyway to close the popup automatically as I open this new tab?
Thanks!
Ryan
Have you tried :
self.close();
There's several ways to do this, but the easiest is just to call:
window.close();
You can even do this in a callback function when you create your tab...
chrome.tabs.create({url: '0_register.html'}, function() {
window.close();
});
You could also add a listener in your background script to check for tab updates, and if your new tab is your registration window, you could remove the popup:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading") {
if(tab.url == "chrome-extension://[extension-id]/0_register.html") {
chrome.tabs.remove(tabId);
}
}
});
chrome.tabs.create({url: '0_register.html', selected: true});
If you don't mind the new tab being selected when it is created, this also forces the popup to close.

Turning bookmarklet into Chrome extension

I'm trying to use loadURI() in a Google Chrome extension so that I can execute a bookmarklet when the toolbar button is pressed.
// in background.html
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('clicked!');
chrome.tabs.executeScript(tab.id, {code: "loadURI('http://www.google.com')"});
});
All I get is 'clicked!' in the log and nothing else happens. No errors. Does anyone know what I'm doing wrong?
loadURI() is a Firefox specific function (docs).
The equivalent in Chrome is the chrome.tabs.update() function as documented here.
The correct code would be:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.update(tab.id, {url: "http://www.google.com"});
});
Remember to include the protocol eg. http: or javascript:

Categories