I am trying to create an extension to analyse requests made on the chrome browser but I can't put it work. The alert never fires.
manifest.json
{
"name": "Test",
"description": "Test",
"version": "1.0",
"manifest_version": 2,
"permissions": ["background", "tabs", "webRequest", "webRequestBlocking", "*://*/*"],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
background.js
var callback = function(details) {
alert("hello");
};
var filter = { "*://*/*" };
var opt_extraInfoSpec = [];
chrome.webRequest.onBeforeRequest.addListener(
callback, filter, opt_extraInfoSpec);
Why is it my alert not firing?
Your filter is the wrong format - it's not a valid object at all. Addtionally it needs to contain at least the 'url' property. If you wan't all URL's, use this:
var filter = {urls: ["<all_urls>"]};
Check out this for exact details on the format for the filter: https://developer.chrome.com/extensions/webRequest#type-RequestFilter
Related
When I run the following function I get a zero for the cookie length:
function cookieinfo() {
chrome.cookies.getAll({}, function(cookie) {
console.log(cookie.length);
allCookieInfo = "";
for (i = 0; i < cookie.length; i++) {
console.log(JSON.stringify(cookie[i]));
allCookieInfo = allCookieInfo + JSON.stringify(cookie[i]);
}
localStorage.allCookieInfo = allCookieInfo;
});
It should be finding all the cookies the user has but I'm getting nothing.
Use: I'm creating a chrome extension that creates a new tab for the user. I'm trying to recreate chromes new tab look and how they display the pages the users already visited.
Here is the manifest.json:
{
"manifest_version": 2,
"name": "-------",
"version": "0.1",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.min.js", "content.js"]
}],
"permissions": ["tabs", "cookies"],
"chrome_url_overrides": {
"newtab": "NewTab.html"
}
}
According to chrome dev docs, "To use the cookies API, you must declare the "cookies" permission in your manifest, along with host permissions for any hosts whose cookies you want to access."
So you need to add "host permissions" in manifest.json like this example
I'm trying to use the webrequest api and I'm having trouble using it to block a website.
manifest.json
{
"manifest_version": 2,
"name": "blocktwitter",
"description": "block twitter",
"version": "1.0",
"permissions": [
"https://ajax.googleapis.com/",
"activeTab",
"storage",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
background.js:
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["https://twitter.com"]},
["blocking"]);
I copied the copy + pasted the url from twitter, and copied the code from the docs, but it's still not working. I'm not sure what I'm doing wrong. Help would be appreciated.
You have two problems.
Problem #1: Invalid match pattern
The first problem is that the URL you are passing to chrome.webRequest.onBeforeRequest.addListener() is not a valid match pattern. Match patterns require a path component. If you had looked at the console for your background page/script you would have seen the following error:
_generated_background_page.html:1 Unchecked runtime.lastError while running webRequestInternal.addEventListener: 'https://twitter.com' is not a valid URL pattern.
Your background.js should be something like:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
console.log('In webRequest');
return {cancel: true};
}, {
urls: ["https://*.twitter.com/*"]
}, ["blocking"]
);
Problem #2: No host permission for twitter.com
You need to have permission for the host that you are blocking. You have to declare the host in your permissions array in manifest.json. Something like:
{
"manifest_version": 2,
"name": "blocktwitter",
"description": "block twitter",
"version": "1.0",
"permissions": [
"https://ajax.googleapis.com/*",
"https://*.twitter.com/*",
"activeTab",
"storage",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"],
"persistent": true
}
}
I'm trying to write an extension to delete some URLs from my history when they are navigated to. Here are the relevant files -
manifest.json
{
"manifest_version": 2,
"name": "Secret",
"description": "Browser History Edits.",
"version": "0.1",
"browser_action": {
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"webNavigation",
"history",
"tabs"
]
}
background.js
var prevent_logging_keywords = ["reddit", "stackoverflow"]
chrome.webNavigation.onBeforeNavigate.addListener(function(details) {
var currentUrl = details.url;
prevent_logging_keywords.forEach(function(keyword) {
if (currentUrl.includes(keyword)) {
console.log(currentUrl);
chrome.history.deleteUrl({ "url": currentUrl}, function(){});
}
});
});
However, this does not work. The URL still shows up in my history and, what's more, the console.log is also never called. What am I doing wrong?
I'm essentially just trying to get the current tab url if they're on youtube.com. I keep getting an error from the script.
Error:
Uncaught TypeError: Cannot call method 'getSelected' of undefined
Manifest
{
"name": "YouTube Fix",
"version": "0.0.1",
"manifest_version": 2,
"description": "Fix some of the annoying little things in YouTube.",
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"content_scripts": [{
"matches": ["http://www.youtube.com/*"],
"js": ["background.js"],
"run_at": "document_start"
}],
"permissions": ["tabs"]
}
Background.js
//this is what is giving me the error:
chrome.tabs.getSelected(null, function (tab) {
myFunction(tab.url);
});
function myFunction(tablink) {
if (tablink == "http://www.youtube.com") {
window.location = "http://www.youtube.com/feed/subscriptions/u";
}
document.getElementById("comments-textarea").disabled = false;
}
The following forks fine, no need for chrome.tabs.getSelected(null, function (tab) {}),because your page always runs for "matches": ["http://www.youtube.com/*"],;
More over add this condition to your code if(document.getElementById("comments-textarea") != null){
Working background.js
if (window.location == "http://www.youtube.com") {
window.location = "http://www.youtube.com/feed/subscriptions/u";
}
if (document.getElementById("comments-textarea") != null) {
document.getElementById("comments-textarea").disabled = false;
}
manifest.json
{
"name": "YouTube Fix",
"version": "0.0.1",
"manifest_version": 2,
"description": "Fix some of the annoying little things in YouTube.",
"content_scripts": [{
"matches": ["http://www.youtube.com/*"],
"js": ["background.js"],
"run_at": "document_start"
}],
"permissions": ["tabs"]
}
Let me know if you need more information.
You're running background.js as a content script rather than a background or event page, and https://developer.chrome.com/extensions/content_scripts.html says that "content scripts have some limitations. They cannot … Use chrome.* APIs (except for parts of chrome.extension)"
Instead, you should put something like
"background": {
"scripts": ["background.js"],
"persistent": false
},
into your manifest. See https://developer.chrome.com/extensions/event_pages.html for more details.
Quoted from here: https://groups.google.com/a/chromium.org/forum/?fromgroups=#!topic/chromium-extensions/A5bMuwCfBkQ
chrome.tabs.getSelected() is deprecated. The following page explains
how to use chrome.tabs.query instead:
http://code.google.com/chrome/extensions/whats_new.html#16 The relevant bit of text is:
"""
The methods getAllInWindow() and getSelected() have been deprecated.
To get details about all tabs in the specified window, use
chrome.tabs.query() with the argument {'windowId': windowID}. To get
the tab that is selected in the specified window, use
chrome.tabs.query() with the argument {'active': true}.
"""
chrome.tabs.getSelected is deprecated. Use chrome.tabs.query instead:
chrome.tabs.query({
"active": true
}, function(tab){
console.log(tab[0]); //selected tab
});
Also, content scripts can not access chrome.tabs APIs. Do this:
chrome.extension.getBackgroundPage().chrome.tabs.query(...
(This might not work. Not tested.)
I wanna make an extension that takes the selected text and searches it in google translate
but I can't figure out how to get the selected text.
Here is my manifest.json
{
"manifest_version": 2,
"name": "Saeed Translate",
"version": "1",
"description": "Saeed Translate for Chrome",
"icons": {
"16": "icon.png"
},
"content_scripts": [ {
"all_frames": true,
"js": [ "content_script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"background": {
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"background",
"tabs"
]
}
and my background.js file
var text = "http://translate.google.com/#auto/fa/";
function onRequest(request, sender, sendResponse) {
text = "http://translate.google.com/#auto/fa/";
text = text + request.action.toString();
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.create({url:text});
});
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]});
and my content_script.js file
var sel = window.getSelection();
var selectedText = sel.toString();
chrome.extension.sendRequest({action: selectedText}, function(response) {
console.log('Start action sent');
});
How do I get the selected text?
You are making it a bit more complicated than it really is. You don't need to use a message between the content script and background page because the contextMenus.create method already can capture selected text. Try adjusting your creations script to something like:
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest});
Then adjust your function to simply get the info.selectionText:
function onRequest(info, tab) {
var selection = info.selectionText;
//do something with the selection
};
Please note if you want to remotely access an external site like google translate you may need to adjust your permissions settings.
I would note - this is no longer valid response if you are moving to manifest version 3. Manifest version 3 adds the concept of "service workers". https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/
You have to update several things, but the basic concept is the same.
manifest.json
"name": "Name of Extension",
"version": "1.0",
"manifest_version": 3,
"description": "Description of Extension",
"permissions": [
"contextMenus",
"tabs",
"activeTab"
],
"background": {
"service_worker": "background.js",
"type": "module"
},
background.js
//Setting up the function to open the new tab
function newTab(info,tab)
{
const { menuItemId } = info
if (menuItemId === 'anyNameWillDo'){
chrome.tabs.create({
url: "http://translate.google.com/#auto/fa/" + info.selectionText.trim()
})}};
//create context menu options. the 'on click' command is no longer valid in manifest version 3
chrome.contextMenus.create({
title: "Title of Option",
id: "anyNameWillDo",
contexts: ["selection"]
});
//This tells the context menu what function to run when the option is selected
chrome.contextMenus.onClicked.addListener(newTab);