Ok so I am trying to get a chrome extension to block mature websites but for some reason it is giving me an error. Here is the error: "Unchecked runtime.lastError: '://.youtube.com' is not a valid URL pattern." and here is the code:
{
"name": "Video Testing",
"version": "1.0",
"description": "Video testing extention",
"permissions": ["webRequest", "webRequestBlocking","<all_urls>"],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
here is background.js
const defaultFilters = [
"*://*.youtube.com"
]
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return { cancel: true}},
{ urls: defaultFilters },
["blocking"]
)
So i hope someone could help me. Thanks!
You forgot a forward slash at the end of the URL. The provided code in the question would not work for me until I added it, and the error appears to come back without it.
const defaultFilters = ["*://*.youtube.com/"]
As stated above, you'll want to use the below format if you wish to block all associated youtube URLs (such as video or channel links) as opposed to just youtube.com
const defaultFilters = ["*://*.youtube.com/*"]
Related
I am trying to make a chrome extension that alerts you in the tab that you are currently moving or highlighting. I have tried reading the chrome migrating to V.3 documentation and have come up with the following code, however, the alerts never appear. Does anybody know what I need to change or add?
// manifest.json
{
"manifest_version": 3,
"name": "Alert",
"version": "0.1",
"description": "alerts you when doing tab functions",
"permissions": ["tabs", "activeTab"],
"host_permissions": ["<all_urls>"],
"background": {
"service_worker": "background.js"
}
}
//background.js
chrome.tabs.onMoved.addListener(function () {
alert("You moved this tab");
});
chrome.tabs.onHighlighted.addListener(function () {
alert("You highlighted this tab");
});
Working directory:
.
├── background.js
├── manifest.json
alert() method cannot be used outside of the browser environment, you can use console.warn() or console.error() instead. But is not a good solution if you want to show an error message to the extension user, as they would never open the console.
If you would like a more user friendly approach use the following:
chrome.notifications.create({
type: 'basic',
iconUrl: '/images/image_if_any.png',
title: `Notification title`,
message: "Your message",
priority: 1
});
Also add "notifications" to "permissions" in your manifest.json file:
"permissions": [..., "notifications"]
alert is not defined in a service worker per specification so we'll have to use console.log
Also, I was looking in the wrong place for the alert messages. I needed to look at the service worker link in my unpacked extension page.
When trying to use Chrome's WebNavigation.onCompleted to run background.js on a certain url I get the error
"Uncaught TypeError: Could not add listener".
For permissions in my manifest.json I have given the extension access to activetab and webrequest.
I have tried using other listeners like
chrome.browserAction.onClicked.addListener
and it worked perfectly. I am also using the latest version of chrome (v73).
background.js :
chrome.webNavigation.onCompleted.addListener(function(tab) {
var eurl = tab.url.split("/skill/");
if(eurl[0] === "https://www.duolingo.com") {
chrome.tabs.executeScript(tab.ib, {
file: 'jquery-3.3.1.min.js'
});
chrome.tabs.executeScript(tab.ib, {
file: 'duohelperinjector.js'
});}
}, {url: [{urlMatches : '*://duolingo.com/skill/*'}]});
manifest.json :
{
"name": "DuoHelper",
"version": "0.0.1",
"manifest_version": 2,
"description": "A Chrome Extension That Helps With Duolingo",
"homepage_url": "https://github.com/TechHax/DuoHelper",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "DuoHelper"
},
"permissions": [
"webNavigation",
"activeTab"
]
}
The error I'm getting:
Uncaught TypeError: Could not add listener
I would, with the extension working properly, like to have the chrome extension inject the javascript files on the active tab if its url is *://duolingo.com/skill/*.
See the documentation: urlMatches is a RE2 regular expression, not a URL match pattern.
Solution 1.
The correct RE2 expression would be 'https?://(www\\.)?duolingo\\.com/skill/.*'
Solution 2.
A better approach is to do a plain string comparison of the host name and path because it's much faster than using regular expressions and the documentation explicitly advises to use regexps only when absolutely unavoidable:
chrome.webNavigation.onCompleted.addListener(info => {
chrome.tabs.executeScript(info.tabId, {file: 'jquery-3.3.1.min.js'});
chrome.tabs.executeScript(info.tabId, {file: 'duohelperinjector.js'});
}, {
url: [{
hostSuffix: '.duolingo.com',
pathPrefix: '/skill/',
}],
});
Note how hostSuffix utilizes an implicit dot added by the API before the first component to match any subdomain of duolingo.com. Also, the callback parameter is not a tab, but a different object with tabId inside.
Solution 3.
Use declarativeContent API as shown in the documentation, but instead of ShowPageAction specify RequestContentScript, which despite the warning in the documentation actually works in the stable Chrome.
This question already has answers here:
TypeError: [API] is undefined in content script or Why can't I do this in a content script?
(2 answers)
Closed 5 years ago.
I am using the Developer Version of Firefox (Version 54.0a2, but also tried the normal Firefox with Version 51) and I want to include notifications in my web extension.
browser["notifications"] does not exist though.
Since it was not working in my extension and I thought maybe something was conflicting I created this very basic web-extension.
the manifest.json:
{
"manifest_version": 2,
"name": "Extension",
"version": "1.0",
"description": "...",
"icons": {
"48": "icons/icon-48.png"
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["test.js"]
}
],
"permissions": ["notifications", "storage"]
}
test.js (storage works just fine btw.)
if (browser["notifications"]) {
console.log('Notifications exist!');
browser.notifications.create({
"type": "basic",
"iconUrl": browser.extension.getURL("icons/icon-48.png"),
"title": "test",
"message": "test"
});
}
else {
//it always executes this part :/
console.log('notifications do not exist');
console.log(browser);
}
Debugging the add-on doesn´t show any errors either.
Many of the apis exclusive for extensions can only be run inside background script. The usual technique if you need to run it from a content script is to send a message from content script to background script, handle the message in background script and run from there the command you wanted.
In your case, there are a few examples at the end of Notification Api, one of them being notify-link-clicks-i18n where you can view how they do the message passing to create the notification from the background script.
I'm trying to build my first Chrome extension but I found problems with debugging.
I'm able to console.log() but in the Developer Tools console (I'm working on the background.js; no UI) there's no report about syntax errors.
Is that normal? Or it depends on some settings of the page I'm creating the extension for? (www.google.com)
I've read maybe there could be a window.onerror set somewhere but I'm not able to find it. I tried a
window.onerror = null;
at the beginning of the background.js but nothing has changed.
What would you do to get the errors back?
UPDATE (Adding code)
This is the manifest.json:
{
"name": "Name",
"description": "Description",
"version": "0.1",
"manifest_version": 2,
"background": {
"persistent": false,
"scripts": ["js/background.js"]
},
"permissions" : [
"tabs",
"*://www.google.com/*",
"*://www.google.de/*"
],
"commands": {
"changeSearch": {
"suggested_key": {
"default": "Ctrl+Shift+A",
"mac": "Command+Shift+A"
},
"description": "Change."
}
}
}
The background.js start like this:
console.log("Start");
chrome.commands.onCommand.addListener(function(command) {
consTYPOTYPOTYPOTYPOTYPOTYPOle.log("catched");
...
I just discovered that errors are thrown if the TYPO is otuside of function(command) code, if I have TYPOs on the 1st or 2nd line.
The 3rd line is totally silent. No error. It just doesn't work.
That's weird to me!
The problem was a conflicting extension that was overriding mine.
Trying to disable all extensions and then re-enabling them, starting from mine, solved the problem.
Probably I made it to have higher priority respect to the conflicting extension (that has been enabled after).
I hope you can help me.
I am trying to create an extension in Chrome which would load a source of the active tab into a variable.
So far I have:
manifest.json
{
"name": "My Extension",
"manifest_version": 2,
"version": "0.1",
"description": "Does some simple stuff",
"browser_action": {
"default_icon": "logo.png"
},
"background": {
"scripts": ["main.js"]}}
main.js
chrome.browserAction.onClicked.addListener(
function(tab) {
var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
});
but that loads the page source of the blank page. What do I need to do to get the source of the active page.
I have done some reading and I think I need to use content script whit some listening functions, I have been searching but all answers seem to me very complicated. Would any of you be so kind to give me some easy example?
Highly appreciate your feedback!
Regards
UPDATE after AdrianCooney answer:
I changed my manifest to contain
"permissions": [
"tabs"
]
Then in main.js I did
chrome.browserAction.onClicked.addListener(function(activeTab) {
chrome.tabs.query({ currentWindow: true, active: true },
function (tabs) {
var ps1=document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
})
});
When I press the Extension button I get something like that
<html></html>
<body><script src="main.js"></script>
</body>
...no matter what tab I have active.
Another try with chrome.tabs.getCurrent
chrome.browserAction.onClicked.addListener(function(activeTab) {
chrome.tabs.getCurrent(
function (tabs) {
var ps1=document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
})
});
The above version of main.js give exact same output as the one before, no matter what page I have active.
Background scripts are isolated from the current page because they're designed to be persistant regardless of the content of the page. You need to use the chrome.tabs API, specifically chrome.tabs.getCurrent. Once you have the current tab, you can inject code into the window. That's where your snippet above comes in.
You will need to add "tab" to your permissions in the manifest file.
As was pointed out, you need to run code in the context of the active tab. One way to do it is using chrome.tabs.executeScript:
chrome.browserAction.onClicked.addListener( function() {
chrome.tabs.executeScript(
{
code: "document.getElementsByTagName('html')[0].innerHTML;"
},
function (ps1) {
window.alert(ps1);
}
);
});
This code under main.js works!!! Thank you guys for your hints they saved me a lot of time!
chrome.browserAction.onClicked.addListener(
function(tab) {
chrome.tabs.executeScript(
null,{
code:"var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);"});
}
);
In Chrome 47 you need to add "activeTab" to permissions, otherwise it doesn't work. With "tabs" it doesn't work.
manifest.json:
{
"name": "Rafi extension",
"manifest_version": 2,
"version": "7",
"description": "Open something",
"browser_action": {
"default_icon": "logo.png"
},
"permissions": [
"activeTab"
],
"background": {
"scripts": ["main.js"]}
}
For anyone looking to do this with Manifest V3, things are much simpler. Let's say you have a script parse_page.js in the root of your extension, that contains whatever code you want to execute:
var ps1 = document.getElementsByTagName('html')[0].innerHTML;
window.alert(ps1);
From the docs, there are two ways to have it execute:
(1) Inject with static declarations: use this method for scripts that that need to run automatically. Simply add the following to your manifest.json:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["parse_page.js"]
}
],
The script will run whenever you visit a new page. You can adjust the matches above if you only want it to execute on certain URLs.
(2) Inject programmatically: use this method for scripts that need to run in response to events or on specific occasions. Add the following to your manifest.json:
"permissions": ["activeTab", "scripting"],
"background": {
"service_worker": "background.js"
},
"action": { }
Next, in background.js, add the following:
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['parse_page.js']
});
});
In this example, the script will run whenever you click on your extension's icon.