Chrome Extension: onclick extension icon, open popup.html in new tab - google-chrome

I have created a chrome extension and managed to open the popup.html file using window.open. however I want to open it in a new tab, I've tried lots of different ways including:
<script type="text/javascript" language="JavaScript">
chrome.tabs.create('url': 'popup.html');
Am I just placing the code in the wrong place or is it the wrong code altogether?

why would you want to open the popup.html in a new tab? You should create a different page for that. Anyways, if you want to open up the popup.html, in a new tab, you would need to pass in the extension url.
http://code.google.com/chrome/extensions/extension.html#method-getURL
chrome.tabs.create({'url': chrome.extension.getURL('popup.html')}, function(tab) {
// Tab opened.
});

Now you can use Event Pages to open popup.html in new tab when extension icon is clicked without creating a default_popup page.
manifest:
"background": {
"scripts": ["background.js"],
"persistent": false
}
js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': chrome.extension.getURL('popup.html'), 'selected': true});
});

Use chrome.tabs.create(Object properties, function callback) as described on http://code.google.com/chrome/extensions/tabs.html
The object properties could contain fields for windowId, index, url and selected. The optional callback function receives a Tab object of the newly created tab.
So the simplest example to create a new tab in the current window and get it selected would look like this:
chrome.tabs.create({'url': chrome.extension.getURL('popup.html')});
Not sure why you would like to show the popup.html in a new tab, but I find it very useful while developing/debugging my extension ... it is quite a pain that on the extension page there is "usually" only a link to the background page.
Would love to know how to open it in a new window and maybe in a kiosk mode ;-)

One complete, worked example:
Manifest.json
{
"manifest_version": 2,
"name": "HelloWorld",
"version": "0.0.1",
"description": "This is HelloWorld",
"author": "BaiJiFeiLong#gmail.com",
"browser_action": {
},
"background": {
"scripts": [
"background.js"
]
}
}
background.js
// Created by BaiJiFeiLong#gmail.com at 2022/4/13
chrome.browserAction.onClicked.addListener(async () => {
await chrome.tabs.create({url: chrome.extension.getURL("popup.html")});
})
popup.html
<!--Created by BaiJiFeiLong#gmail.com at 2022/4/13-->
<body style="min-width: 500px">
<h1>Hello World</h1>
</body>

Related

Chrome extension push notifications on signalR event

I'm working on building an chrome extension that communicates with an external SignalR HUB on server side.
I've managed to configure both to communicate with one another if I write the JS code in the pop-up page, the problem with this method is that if the extension is not opened, then it can't get updates (doesn't respond to the raised event).
In order to solve it I read that I should write my event handlers in the background.js, so even if the extension pop up is not showing - it would still respond to the event. However, I still need to support a button click on my extension to fire an event - which after reading a bit more is not possible cause I don't have access to the DOM in a background file.
So my question is how do I tackle this issue? how can I, from the client side call a function (or make ajax requests) in the server SignalR HUB? and also receive a response from the server when the popup is not opened.
By response I mean a to update values in the background.js and a simple +1 to the value in the icon badge, Something that will notify the user that something happened.
I'm very new to chrome extensions so I would appreciate the help!
This is my current code:
manifest.json
{
"manifest_version": 2,
"name": "Getting started ex1ample",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"background": {
"scripts": ["jquery-2.1.4.min.js", "jquery.signalR-2.2.0.min.js", "background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"http://localhost:61275/"
]
}
background.js
var singalR = {};
$(document).ready(function(){
singalR.connection = $.hubConnection('http://localhost:61275/signalr/hubs', {useDefaultPath: false});
singalR.connection.logging = true;
singalR.roomIndexHubProxy = singalR.connection.createHubProxy('roomIndexHub');
singalR.connection.start().done(function() {
// Wire up Send button to call RoomIndexHubProxy on the server.
console.log('Hub has started');
$("#btn-join").click(function(){
singalR.roomIndexHubProxy.invoke('test', 111);
});
});
singalR.connection.error(function (error) {
console.log('SignalR error: ' + error)
});
singalR.roomIndexHubProxy.on('test', function (val) {
chrome.browserAction.setBadgeText({ text: val } );
});
});
popup.html
<!doctype html>
<html>
<head>
<script src="popup.js"></script> //empty for now
</head>
<body>
<button id="btn-join">Join</button>
</body>
</html>
Server Side HUB
public class RoomIndexHub : Hub
{
static int val = 0;
public RoomIndexHub(){
}
public async Task test(int k)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<RoomIndexHub>();
val++;
await Task.Delay(4000);
hubContext.Clients.All.test(val.ToString());
}
}
Have you tried setting the lifetime of your background page? Set persistence to true so this hidden page in background will "live" all the time and is able to listen to incoming requests.
"background": {
"scripts": ["background.js"],
"persistent": true
},
This will give you a persistent background page.
Check this: Chrome documentation for event pages
Reards
Carsten

Chrome Extension: Open an URL on click?

I'm currently trying to make sense of Google Chrome Extension development, but I'm having issues understanding it correctly.
I'm developing an extension that hosts a list of URLs and opens them on click. This sounds like a trivial task, but it doesn't work. Probably I'm doing something blatantly wrong.
Screenshot
It's not styled, but that's step 2. Basically, I want to open a shortcut on click:
manifest.json
{
"manifest_version": 2,
"name": "Chrome Shortcuts",
"description": "This extension provides shortcuts to locations in Google Chrome",
"version": "1.0.0",
"browser_action":
{
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts":
[
{
"js": [ "popup.js" ],
"matches": [ "http://*/*", "https://*/*" ]
}
],
"permissions":
[
"tabs",
"http://*/*"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Chrome Shortcuts</title>
<script src="popup.js"></script>
</head>
<body>
<ul>
<li>Settings - Passwords</li>
</ul>
</body>
</html>
popup.js
function OpenShortcut(location)
{
chrome.tabs.create({ url: location });
}
You cannot open chrome:// URLs using standard methods. This is a privileged page and the navigation will fail.
Instead, you need to use tabs API. Specifically,
chrome.tabs.create({url: "chrome://settings/passwords"});
Add active: false if you need it to open in background without closing the popup.
I completely missed the fact you're doing it already, sorry! The issue is with trying to activate your code with href="javascript:[some code]".
This, as well as onclick="[some code]", will fail in a Chrome extension due to the Content Security Policy. Specifically, inline code is not allowed (and you cannot modify the CSP in a way that allows it).
The docs give a solution to this - assign the handler from your code, i.e.
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('link1').addEventListener('click', function() {
OpenShortcut('chrome://settings/passwords');
});
});
For this to work, add an id attribute to your links. DOMContentLoaded wrapper is required, since your popup.js is executed before your node exists in the DOM.

How chrome extension will listen when navigated any website?

I need a listener in my chrome extension that can listen when a web site will navigate then the extension will collect the navigated url.
What you want here is the chrome.tabs.onUpdated listener, that will fire every time a tab changes URL and loads a new page.
To do this you'll need to follow two simple steps:
Add the tabs permission to your manifest.json, so it will look like this:
{
"manifest_version": 2,
"name": "Extension name",
"description": "Your description...",
"version": "1",
"permissions": [
"<all_urls>",
"tabs"
],
"background": { "scripts": ["background.js"] }
}
Now, in your background.js you can add the listener, that will look like this:
chrome.tabs.onUpdated.addListener(function(tabID, info, tab) {
var tabURL = tab.url;
// here is the url of the tab
// now you can do whatever you want with it
});
I strongly suggest you to take a look at the other methods and objects of the tabs API, so you may find helpful the official documentation for chrome.tabs
.

disable refresh / back / forward in OWN browser

Is there a way to only make my OWN browser (Chrome) not be able to go back / forward / refresh?
This happens rather often that when Im developing and playing around in devtools (Changing HTML and CSS just to try things out) I sometimes accidentally swipe back or out of habit hit refresh. I would like to be able to disable the back or forward button via some sort of extension?
I am NOT trying to disable the button on any live-website, just for me locally. Any ideas?
If you want to prevent accidental navigations, there's no need to install any extension. Just open the console, and run the following code:
window.onbeforeunload = function() {
return 'Want to unload?';
};
With this code, you will get a confirmation prompt.
If you really want to prevent the page from unloading via an extension, use the technique described in the answers to How to cancel webRequest silently in chrome extension.
Here's a minimal demo extension that adds a button to your browser. Upon click, you cannot navigate to a different page any more. You can still close the tab without any warning, though:
// background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var scheme = /^https/.test(details.url) ? 'https' : 'http';
return { redirectUrl: scheme + '://robwu.nl/204' };
// Or (seems to work now, but future support not guaranteed):
// return { redirectUrl: 'javascript:' };
}, {
urls: ['*://*/*'],
types: ['main_frame'],
tabId: tab.id
}, ['blocking']);
});
manifest.json for this extension:
{
"name": "Never unload the current page any more!",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": true
},
"browser_action": {
"default_title": ""
},
"permissions": [
"<all_urls>",
"webRequest",
"webRequestBlocking"
]
}

Create new tab from browserAction in Chrome [duplicate]

How can I create an extension for Chrome that adds an icon to the toolbar, and when you click it, it opens a new tab with some local web page (for example: f.html)?
I saw this question, but it doesn't really explains what should I add in the manifest file...
This is not true for newer chrome apps.
Newer chrome apps having manifest_version: 2
requires the tabs be opened as:
chrome.browserAction.onClicked.addListener(function(activeTab)
{
var newURL = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
chrome.tabs.create({ url: newURL });
});
Well, in the extensions docs, it states in manifest, you would need to include "tabs" as its permission. Same way they explain the hello world application:
Manifest File:
{
"name": "My Extension",
"version": "1.0",
"description": "Opens up a local webpage",
"icons": { "128": "icon_128.png" },
"background_page": "bg.html",
"browser_action": {
"default_title": "",
"default_icon": "icon_19.png"
},
"permissions": [
"tabs"
],
}
Within the background page, you listen to the mouse click event on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': chrome.extension.getURL('f.html')}, function(tab) {
// Tab opened.
});
});
As you noticed above, you will see that I used the question you saw in the other post. Note, this isn't tested, but I believe it should work.
chrome.tabs.create need the permission of "tabs".
Simply using window.open in extension without need of any permission. and the code is shorter. I suggest this solution.
window.open(url,'_blank');