How to show Chrome Extension on certain domains? - google-chrome

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

Related

Content script code is not being executed

I've taken a look at other related SO posts and the solutions haven't helped solve my issue. This is my first chrome extension, so please bear with me!
I'm writing a simple chrome extension that searches for user provided keywords on a webpage. I can't get the content script that returns the DOM content to run. Some of the code, I've taken from an answer in another SO post, but I can't seem to get it to work for me.
I put a console.log("hello world") at the top of the file, and it doesn't show up, so I think it might be the structure of my project.
manifest.json
{
"name": "keyword search",
"version": "0.0.1",
"manifest_version": 2,
"permissions": [ "tabs" , "storage", "activeTab", "<all_urls>"],
"browser_action": {
"default_popup": "html/form.html"
},
"content_scripts": [{
"matches": [ "<all_urls>" ],
"js": [ "js/jquery.min.js", "content_scripts/content_script.js" ]
}],
"homepage_url": "http://google.com/"
}
js/popup.js
function run() {
running = true;
console.log('running');
var url = "https://www.stackoverflow.com/"
// Get KW & category for search
chrome.storage.local.get(["kw"],
function (data) {
kw = data.kw;
console.log("redirecting to find kw: " + kw);
// Send current tab to url
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.update(tabs[0].id, {url: url});
chrome.tabs.sendMessage(tabs[0].id, {type: 'DOM_request'}, searchDOM);
});
}
);
}
function searchDOM(domContent) {
console.log("beginning dom search \n" + domContent);
}
content_scripts/content_script.js
// Listen for messages
console.log("hello world")
chrome.runtime.onMessageExternal.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.type === 'DOM_request') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
console
running
redirecting to find kw: TestKeyword
beginning dom search
undefined
First, onMessageExternal is the wrong event (it's for external messaging):
you should use the standard onMessage.
Second, chrome extensions API is asynchronous so it only registers a job, returns immediately to continue to the next statement in your code without waiting for the job to complete:
chrome.tabs.update enqueues a navigation to a new URL
chrome.tabs.sendMessage enqueues a message sending job
the current page context in the tab gets destroyed along with the running content scripts
the tab starts loading the new URL
the message is delivered into the tab but there are no listeners,
but this step may instead run right after step 2 depending on various factors so the content script running in the old page will receive it which is not what you want
the tab loads the served HTML and emits a DOMContentLoaded event
your content scripts run shortly after that because of the default "run_at": "document_idle"
There are at least three methods to properly time it all:
make your content script emit a message and add an onMessage listener in the popup
use chrome.tabs.onUpdated to wait for the tab to load
use chrome.tabs.onUpdated + chrome.tabs.executeScript to simplify the entire thing
Let's take the executeScript approach.
remove "content_scripts" from manifest.json
instead of chrome.tabs.query (it's not needed) use the following:
chrome.tabs.update({url}, tab => {
chrome.tabs.onUpdated.addListener(function onUpdated(tabId, change, updatedTab) {
if (tabId === tab.id && change.status === 'complete') {
chrome.tabs.onUpdated.removeListener(onUpdated);
chrome.tabs.executeScript(tab.id, {
code: 'document.documentElement.innerHTML',
}, results => {
searchDOM(results[0]);
});
}
});
});

Google chrome extension error

chrome-extension, stucked with the error
Uncaught TypeError: Cannot read property 'sendRequest' of undefined
here is my code
manifest.json
{
"manifest_version": 2,
"name": "blah",
"version": "1.0",
"description": "blah",
"browser_action": {
"default_icon": "icon.png"
},
"background": "bg.html", // change to your background page
"permissions": ["http://*/*", "tabs"], //need permission to access all pages & tabs
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"], // run for http & https pages
"js": ["key_event.js"], // key_event.js is injected to the page, this handles key press
"run_at": "document_start" // run before everything else, else there will be conflicts at pages which accept keyboard inputs ( eg:google search)
}
]
}
key_event.js
if (window == top) {
window.addEventListener('keyup', doKeyPress, false); //add the keyboard handler
}
function doKeyPress(e){
if (e.keyCode == 17){ // if e.shiftKey is not provided then script will run at all instances of typing "G"
alert("pressed");
chrome.extension.sendRequest({redirect: "https://www.google.co.in"});//build newurl as per viewtext URL generated earlier.
}
}
bg.html
chrome.extension.onRequest.addListener(function(request, sender) {
chrome.tabs.update(sender.tab.id, {url: request.redirect});
});
plz help me
As already mentioned in comments
The background section of manifest version 2 has to be like
"background": {"scripts": ["bg.js"]}
There is no background page, only background scripts. So you'll have to move your code from bg.html to bg.js and remove all the extra HTML from it.
chrome.extension.sendRequest and chrome.extension.onRequest have been deprecated in favor of chrome.runtime.sendMessage and chrome.runtime.onMessage respectively. That means, you can still use sendRequest and onRequest but it might be subject to removal in a future version of Chrome
The keyCode for G is 71 rather than 17

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

How to make Chrome auto choose the search engine based on a pattern in the typed text?

Use case: user types something like:
AA1234↵ - i want the browser to directly go to http://example.com/search/%s
ZZ666↵ - i want the browser to directly go to http://acme.com/search/%s
fallback not normal search for non matching patterns
I'm sure that this cannot be just configured, so it would require probably to write an extension (if possible).
from this example: omnibox-multipe-keyword
manifest.json:
{
"background": {
"scripts": ["background.js"]
},
"description": "Parse XXX-000 pattern from entered url for google search and redirect to Jira",
"name": "Jira Search",
"permissions": [ "tabs" ],
"version": "1",
"minimum_chrome_version": "9",
"manifest_version": 2
}
background.js:
function navigate(url) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.update(tab.id, {url: url});
});
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading") {
if(/google\.com.+search\?q.\w+\-\d+/.test(tab.url)) {
var ticket = /\w+\-\d+/.exec(tab.url)
navigate("http://jira..../QuickSearch.jspa?searchString="
+ ticket[0]);
}
}
});
this simple check \w+-\d+/ regexp in google search and if found - redirect to jira search...
The best you can do is use the Omnibox API. You will have to define a keyword (xyz) and when a user enteres xyz + tab + search query your extension will get search query and can decide what page to open.

How can I get the URL of the current tab from a Google Chrome extension?

I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?
Use chrome.tabs.query() like this:
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
// use `url` here inside the callback because it's asynchronous!
});
This requires that you request access to the chrome.tabs API in your extension manifest:
"permissions": [ ...
"tabs"
]
It's important to note that the definition of your "current tab" may differ depending on your extension's needs.
Setting lastFocusedWindow: true in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).
Setting currentWindow: true allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.
I chose to use lastFocusedWindow: true in this example, because Google calls out cases in which currentWindow may not always be present.
You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query
Warning! chrome.tabs.getSelected is deprecated. Please use chrome.tabs.query as shown in the other answers.
First, you've to set the permissions for the API in manifest.json:
"permissions": [
"tabs"
]
And to store the URL :
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
});
Other answers assume you want to know it from a popup or background script.
In case you want to know the current URL from a content script, the standard JS way applies:
window.location.toString()
You can use properties of window.location to access individual parts of the URL, such as host, protocol or path.
The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:
var tablink;
chrome.tabs.getSelected(null,function(tab) {
tablink = tab.url;
});
console.log(tablink);
The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.
Try something like:
chrome.tabs.getSelected(null, function(tab) {
myFunction(tab.url);
});
function myFunction(tablink) {
// do stuff here
console.log(tablink);
}
This is a pretty simple way
window.location.toString();
You probaly have to do this is the content script because it has all the functions that a js file on a wepage can have and more.
Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)
Additionally it is a nice working code example, which i prefer motstly over reading Documents.
Can be found here:
Email this page
This Solution is already TESTED.
set permissions for API in manifest.json
"permissions": [ ...
"tabs",
"activeTab",
"<all_urls>"
]
On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated
chrome.tabs.onActivated.addListener((activeInfo) => {
sendCurrentUrl()
})
On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged
chrome.tabs.onSelectionChanged.addListener(() => {
sendCurrentUrl()
})
the function to get the URL
function sendCurrentUrl() {
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url
console.log(tablink)
})
async function getCurrentTabUrl () {
const tabs = await chrome.tabs.query({ active: true })
return tabs[0].url
}
You'll need to add "permissions": ["tabs"] in your manifest.
For those using the context menu api, the docs are not immediately clear on how to obtain tab information.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log(info);
return console.log(tab);
});
https://developer.chrome.com/extensions/contextMenus
You have to check on this.
HTML
<button id="saveActionId"> Save </button>
manifest.json
"permissions": [
"activeTab",
"tabs"
]
JavaScript
The below code will save all the urls of active window into JSON object as part of button click.
var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
myArray = [];
chrome.tabs.query({"currentWindow": true}, //{"windowId": targetWindow.id, "index": tabPosition});
function (array_of_Tabs) { //Tab tab
arrayLength = array_of_Tabs.length;
//alert(arrayLength);
for (var i = 0; i < arrayLength; i++) {
myArray.push(array_of_Tabs[i].url);
}
obj = JSON.parse(JSON.stringify(myArray));
});
}, false);
If you want the full extension that store the URLs that opened or seen by the use via chrome extension:
use this option in your background:
openOptionsPage = function (hash) {
chrome.tabs.query({ url: options_url }, function (tabs) {
if (tabs.length > 0) {
chrome.tabs.update(
tabs[0].id,
{ active: true, highlighted: true, currentWindow: true },
function (current_tab) {
chrome.windows.update(current_tab.windowId, { focused: true });
}
);
} else {
window.addEventListener(hash, function () {
//url hash # has changed
console.log(" //url hash # has changed 3");
});
chrome.tabs.create({
url: hash !== undefined ? options_url + "#" + hash : options_url,
});
}
});
};
you need index.html file also. which you can find in the this Github
the manifest file should be like this:
{
"manifest_version": 2,
"name": "ind count the Open Tabs in browser ",
"version": "0.3.2",
"description": "Show open tabs",
"homepage_url": "https://github.com/sylouuu/chrome-open-tabs",
"browser_action": {},
"content_security_policy": "script-src 'self' https://ajax.googleapis.com https://www.google-analytics.com; object-src 'self'",
"options_page": "options.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"web_accessible_resources": ["img/*.png"],
"permissions": ["tabs", "storage"]
}
The full version of simple app can be found here on this Github:
https://github.com/Farbod29/extract-and-find-the-new-tab-from-the-browser-with-chrome-extention