disable refresh / back / forward in OWN browser - google-chrome

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"
]
}

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 webNavigation.onComplete not working?

I'm trying to write a chrome extension that executes some code when the user is on a youtube page with a video. As far as I can tell, my code is correct, but It isn't working.
eventPage.js:
chrome.webNavigation.onCompleted.addListener(function(){
console.log("Test")
},{url: [{pathContains: "watch", hostSuffix: "youtube.com"}]});
and my manifest file
{
"manifest_version": 2,
"name": "youtubeExtension",
"description": "A chrome extension for youtube",
"version": "0.1",
"permissions": ["https://www.youtube.com/", "webNavigation"],
"background": {
"scripts": ["eventPage.js"],
"persistant": false
}
}
It seems onCompleted doesn't work on youtube.
Instead of using webNavigation you can also use
Add this to your background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
if (tab.url.indexOf("youtube.com") != -1) {
alert("Youtube load complete");
injectScripts();
}
}
});
and add the following to your mainfest.json
"permissions": ["https://www.youtube.com/", "webNavigation","tabs"]
This will work just as well
chrome.webNavigation.onCompleted is only triggered when a document has finished loading. When you navigate to a different page on YouTube, the new page is not really "loaded" in a traditional way, but the page is dynamically updated, and the URL is replaced using history.pushState. To detect this kind of "navigations", use the chrome.webNavigation.onHistoryStateUpdated event in addition to the onCompleted event.
Another way to detect videos on YouTube pages is by using content scripts on YouTube and some event specific to YouTube, see this answer.

How to show Chrome Extension on certain domains?

I'm writing my first Chrome Extension. I've used permission, but I'm seeing my button everywhere.
How can I only show the button on the addresses I'm writing the extension for?
Although the answer from #Sorter works, it is not the best way to solve the problem.
First and foremost, it does not always work. If the page used history.pushState, the page action will disappear and not come back until you trigger the onUpdated or onHighlighted event again Chromium issue 231075.
Secondly, the method is inefficient, because it's triggered for every update of tab state on all pages.
The most efficient and reliable way to get a page action to appear on certain domains is to use the declarativeContent API. This is only available since Chrome 33. Before that, the webNavigation API was the most suitable API. The advantage of these API over the method using the tabs API is that you can safely use event pages, because you can declare URL filters. With these URL filters, the events will only be triggered if you navigate to a page that matches the URL filters. Consequently, your extension/event page will not be activated until really needed (= no wasted RAM or CPU).
Here's a minimal example (background.js) using the webNavigation API:
function onWebNav(details) {
if (details.frameId === 0) {
// Top-level frame
chrome.pageAction.show(details.tabId);
}
}
var filter = {
url: [{
hostEquals: 'example.com'
}]
};
chrome.webNavigation.onCommitted.addListener(onWebNav, filter);
chrome.webNavigation.onHistoryStateUpdated.addListener(onWebNav, filter);
manifest.json:
{
"name": "Name ",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_title": "Only visible on stackoverflow.com"
},
"permissions": [
"webNavigation"
]
}
If you target Chrome 33 and higher, then you can also use the declarativeContent API instead. Simply replace the "webNavigation" permission with "declarativeContent", and use the following background script (background.js):
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'example.com'
}
})
],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
In both examples, I used a UrlFilter that matches the example.com domain.
Create background.js which checks for updated and highlighted tab.
function checkForValidUrl(tabId, changeInfo, tab) {
// If 'example.com' is the hostname for the tabs url.
var a = document.createElement ('a');
a.href = tab.url;
if (a.hostname == "example.com") {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);
//For highlighted tab as well
chrome.tabs.onHighlighted.addListener(checkForValidUrl);
Create popup.html and popup.js in the similar manner.
You can use the variables defined in background.js in content scripts (popup.js) with
chrome.extension.getBackgroundPage().variableName
Here's the example extention download link.
For your reference and ease, here's the sample manifest.json file
{
"manifest_version": 2,
"name": "Example Extension",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"page_action":{
"default_icon": "images/icon_16.png",
"default_popup": "popup.html",
"default_title": "Title for the extension"
},
"permissions": [
"tabs"
]
}
An Updated Way:
I use the following with great success:
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
var url = info.url || tab.url;
if(url && url.indexOf('example.com') > -1)
chrome.pageAction.show(tabId);
else
chrome.pageAction.hide(tabId);
});

Redirecting http to https using a Chrome extension

I am developing a number of Node.js applications that use an https server. While I am developing them, I run them on localhost using a self-signed certificate. Basically, everything works, but I have two issues:
When I point my browser to https://localhost:3000 for the first time, it warns me about a non-trusted certificate. This is, of course, true (and important), but it's annyoing while developing. Of course, I could add the certificate as a trusted one, but they change from time to time, and I don't want to clutter the certificate store.
Sometimes I just forget to enter the https part into the address bar, so Chrome tries to load the website using http. For whatever reason Chrome does not realize that there is no webserver responding to httprequests, instead it loads and loads and loads and …
What I would like to do to solve both issues is to create a Chrome extension that resides next to the address bar and offers a button with which you can toggle its state:
If the extension is disabled, it does nothing at all.
If the extension is enabled, and you send a request to localhost (and only then!), it shall do two things:
If the request uses http, but the page is still pending after a few seconds, it shall try using https instead.
Temporarily accept any certificate, no matter whether it's trusted by the browser or not.
To make it explicit: These rules shall only active for localhost.
So, now my questions are:
Is something like this possible using a Chrome extension at all?
As I have absolutely zero experience with writing Chrome extension, what would be a good starting point, and what terms should I look for on Google?
The Google Chrome Extensions Documentation is a great place to start. Everything you describe is possible using a Chrome Extension except for the "certificate accepting" part. (I am not saying it is not possible, I just don't know if it is - but I would be very surprised (and concerned) if it were.)
Of course, there is always the --ignore-certificate-errors command-line switch, but it will not differentiate between localhost and other domains.
If you decide to implement the rest of the functionality, I suggest looking into chrome.tabs and/or chrome.webRequest first. (Let me, also, mention "content scripts" are unlikely to be of any use.)
That said, below is some code for a demo extension (just to get you started).
What is does:
When deactivated -> nothing
When activated -> Listens for tabs being directed to URLs like http://localhost[:PORT][/...] and redirects them to https (it does not wait for a response or anything, it just redirects them instantly).
How to use:
Click the browser-action icon to activate/deactivate.
It's not perfect/complete, of course, but it's a starting point :)
Extension directory structure:
extention-root-directory/
|_____ manifest.json
|_____ background.js
|_____ img/
|_____ icon19.png
|_____ icon38.png
manifest.json:
(See here for more info on the possible fields.)
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"default_locale": "en",
"offline_enabled": true,
"incognito": "split",
// The background-page will listen for
// and handle various types of events
"background": {
"persistent": false, // <-- if you use chrome.webRequest, 'true' is required
"scripts": [
"background.js"
]
},
// Will place a button next to the address-bar
// Click to enable/disable the extension (see 'background.js')
"browser_action": {
"default_title": "Test Extension"
//"default_icon": {
// "19": "img/icon19.png",
// "38": "img/icon38.png"
//},
},
"permissions": [
"tabs", // <-- let me manipulating tab URLs
"http://localhost:*/*" // <-- let me manipulate tabs with such URLs
]
}
background.js:
(Related docs: background pages, event pages, browser actions, chrome.tabs API)
/* Configuration for the Badge to indicate "ENABLED" state */
var enabledBadgeSpec = {
text: " ON ",
color: [0, 255, 0, 255]
};
/* Configuration for the Badge to indicate "DISABLED" state */
var disabledBadgeSpec = {
text: "OFF",
color: [255, 0, 0, 100]
};
/* Return whether the extension is currently enabled or not */
function isEnabled() {
var active = localStorage.getItem("active");
return (active && (active == "true")) ? true : false;
}
/* Store the current state (enabled/disabled) of the extension
* (This is necessary because non-persistent background pages (event-pages)
* do not persist variable values in 'window') */
function storeEnabled(enabled) {
localStorage.setItem("active", (enabled) ? "true" : "false");
}
/* Set the state (enabled/disabled) of the extension */
function setState(enabled) {
var badgeSpec = (enabled) ? enabledBadgeSpec : disabledBadgeSpec;
var ba = chrome.browserAction;
ba.setBadgeText({ text: badgeSpec.text });
ba.setBadgeBackgroundColor({ color: badgeSpec.color });
storeEnabled(enabled);
if (enabled) {
chrome.tabs.onUpdated.addListener(localhostListener);
console.log("Activated... :)");
} else {
chrome.tabs.onUpdated.removeListener(localhostListener);
console.log("Deactivated... :(");
}
}
/* When the URL of a tab is updated, check if the domain is 'localhost'
* and redirect 'http' to 'https' */
var regex = /^http(:\/\/localhost(?::[0-9]+)?(?:\/.*)?)$/i;
function localhostListener(tabId, info, tab) {
if (info.url && regex.test(info.url)) {
var newURL = info.url.replace(regex, "https$1");
chrome.tabs.update(tabId, { url: newURL });
console.log("Tab " + tabId + " is being redirected to: " + newURL);
}
}
/* Listen for 'browserAction.onClicked' events and toggle the state */
chrome.browserAction.onClicked.addListener(function() {
setState(!isEnabled());
});
/* Initially setting the extension's state (upon load) */
setState(isEnabled());

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');