I am new to Chrome Extensions and I unable to find how to inject content.js to a specific URL only? I want the user to give me a specific URL and then inject the content.js to that specific URL. As of right now, my content script is being injected in all URLs. I am guessing there is something wrong in my Manifest.json or background.js or both since I am not sure if I used the executeScript function correct.
Right now I am only designing my code to not inject content.js to google.com but once I know the solution to this problem then it would be designed to specific URLs. I would appreciate any help, thank you.
manifest.json
{
"name": "Chrome Extension",
"description": "Test Chrome Extension",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting", "tabs"],
"content_scripts": [
{
"all_frames" : false,
"matches": ["http://*/", "https://*/*"],
"js": ["contentscript.js"],
"css": ["contentscript.css"],
"run_at": "document_end"
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/16x16.png",
"32": "/images/32x32.png",
"48": "/images/48x48.png",
"128": "/images/128x128.png"
}
},
"icons": {
"16": "/images/16x16.png",
"32": "/images/32x32.png",
"48": "/images/48x48.png",
"128": "/images/128x128.png"
},
"host_permissions": ["http://*/", "https://*/*"],
"options_page": "options.html"
}
background.js
// keep track of the URL when user changes URL in current tab
try {
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == "complete") {
let testURL = new URL(tab.url);
// not allowed to inject content.js on chrome://
// testing to see if my content.js will not be injected to google.com but it still is
if (!testURL.origin.includes('chrome') && !tab.url.includes('google')) {
if (changeInfo.status == 'complete') {
chrome.scripting.executeScript({
files: ['contentscript.js'],
target: {tabId: tab.id}
});
console.log(testURL.hostname);
}
} else {
console.log('Invalid URL onUpdated');
}
}
});
} catch (e) {
console.log(e);
}
// when user changes to a different tab, get URL of that tab
try {
chrome.tabs.onActivated.addListener(function(activeInfo) {
getCurrentTab();
} catch (e) {
console.log(e);
}
function getCurrentTab() {
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
let tab_Id = tabs[0].id;
try {
let urlConstr = new URL(url);
if (!urlConstr.origin.includes('chrome') && !url.includes('google')) {
chrome.scripting.executeScript({
files: ['contentscript.js'],
target: {tabId: tab_Id}
});
console.log('changed content here');
} else {
console.log('chrome website or google.com, don't inject content.js nothing');
}
} catch(e) {
console.log('ERROR HAPPENED - ' + e);
}
});
}
Related
For work we often get log files with links in them, these are not provided with a <h ref tag and are therefore plain text in the log files. the purpose is that this script converts the links to a real h ref. so that you can click on it.
I'm trying to build a chrome extension, it already contains a popup with certain functions and it works.
I also want to build in a function that reads all websites and converts non-clickable links into clickable links.
I have part of the code but I can't get it to work...
background.js(problem with the id ):
chrome.scripting.executeScript({
target: {tabId: id, allFrames: true},
files: ["/content_scripts/clickablelinks.js"],
});;
clickablelinks.js:
// Make links clickable.
console.log("Script started");
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
console.log("Tab updated: " + tabId);
chrome.tabs.executeScript(tabId, {
code: `
console.log("Script executed");
var links = document.querySelectorAll("a[href^='http'], a[href^='https']");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
window.open(this.href);
return false;
}
}
$('body *').each(function() {
var html = $(this).html();
var newHtml = html.replace(/([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})/gi, '$1');
newHtml = newHtml.replace(/((https?|ftp):\/\/[^\s\/$.?#,\(\)].[^\s,]*)/gi, '$1');
newHtml = newHtml.replace(/(((www.)?)([A-Z0-9])([^\s,]*)\.(eu|com|be|co\.uk|net|org|edu|gov|ca|de|fr|us|ru|ch|it|nl|se|no|es|ly|am)([^\s,\(\)]*))/gi, '$1');
newHtml = newHtml.replace(/((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))/gi, '$1');
$(this).html(newHtml);
});
`
});
console.log("Script ended");
});
manifest.json:
{
"name": "Tech Tools",
"content_scripts": [{
"all_frames": true,
"matches": ["***private***"],
"js": ["/js/content.js"],
"run_at": "document_idle"
}],
"description": "Easy shortcuts!",
"version": "3.2.5",
"manifest_version": 3,
"background": {
"service_worker": "/js/background.js"
},
"permissions": ["storage", "tabs", "activeTab", "scripting", "background"],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/icon16.png",
"32": "/images/icon32.png",
"48": "/images/icon48.png",
"128": "/images/icon128.png"
}
},
"icons": {
"16": "/images/icon16.png",
"32": "/images/icon32.png",
"48": "/images/icon48.png",
"128": "/images/icon128.png"
},
"options_page": "options.html"
}
In hope for a bit help, kind regards...
some suggestions our a result...
I'm trying to build an extension to monitor the xhr portion of the devtools network tab. With some help , I have been able to get the requests to be displayed on the service-worker console and I can log the Post requests. I'm also now saving the data "point" in chrome.storage. My next step is to read the data from chrome.storage.local, and have the content script log it to the console. However although I am getting no errors, I don't see any output in the console. No errors seen though. What am I doing wrong?
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": ["*://*.cnn.com/"],
"permissions": ["webRequest", "activeTab","tabs"],
"content_scripts": [
{
"matches": ["*://cnn.com/*"],
"js": ["popup.js"]
}
]
}
In my background.js:
(function () {
var point;
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
point = body.CenterPoint.Point;
console.log(point);
chrome.storage.local.set({ 'key': point }, function () {
console.log('Value is set to ' + point);
});
},
{ urls: [url] },
["requestBody"]
);
})();
popup.js:
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${namespace}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`
);
}
});
manifest.json
{
"manifest_version": 2,
"name": "Project",
"description": "Chrome Extension for sending messages",
"version": "1.0",
"browser_action": {
"default_icon": "red_dot.png"
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/",
"storage"
],
"background" : {
"scripts" : ["background.js"]
},
"content_scripts": [
{
"matches":["https://www.website.com/*"],
"js":["keypress.js", "jquery.js", "js_file.js"],
"run_at": "document_end"
}
]
}
background.js
var running = false
chrome.browserAction.onClicked.addListener(function(tab) {
if (running) {
alert('script is running, turning off');
chrome.browserAction.setIcon({path: "red_dot.png"})
running = false
} else {
alert('script is not running, turning on');
chrome.browserAction.setIcon({path: "green_dot.jpg"})
running = true
}
});
When I click on the icon, I get the popup as expected, but the icon itself isn't changing.
I'm getting this error:
Unchecked runtime.lastError: Icon invalid.
but I don't understand why. The code seems valid.
use this api and carefully enter params specifically path
https://developer.chrome.com/extensions/browserAction#method-setIcon
I am making a chrome extension it will get me to certain page by autoclicking. Since it goes from page to page. I am not able to get past after the first page. I am not able to do when the second page loads after first click
manifest.json
{
"manifest_version": 2,
"name": "AutoClick",
"description": "This autoclicks",
"version": "1.1",
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"content_scripts": [{
"matches": ["*://*.blogger.com/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}],
"permissions": [
"activeTab",
"tabs",
"*://*.blogger.com/*"
]
}
background.js
chrome.tabs.create
chrome.browserAction.onClicked.addListener(function (tab) {
var newURL = "https://draft.blogger.com/blog/posts/3778735982367012067";
chrome.tabs.create({ url: newURL });
chrome.tabs.executeScript({ file: "content.js" });
});
content.js
function createpost(){
document.querySelector('.CwaK9').click()
}
function video1(){
document.querySelector('.vde74d').click()
}
if (window.location.href == "https://draft.blogger.com/blog/posts/3778735982367012067") {
createpost()
newFunction()
}
function newFunction() {
if (window.location.href.match('https://draft.blogger.com/blog/posts/3778735982367012067/')) {
video1();
}
}
using match because it add random ID to end of the URL after first click.
It works fine during first click but when the next page loads it don't.
I have a simple chrome extension that auto-fills the form on a page with default values.
manifest.json file
{
"manifest_version": 2,
"name": "Form Filler",
"description": "This extension auto fills form in a specific page.",
"version": "1.0",
"icons": {
"128": "128x128.png"
},
"page_action": {
"default_icon": "19x19.png",
"default_popup": "popup.html",
"default_title": "Form Filler"
},
"options_page":"options.html",
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"content_scripts":[
{
"matches": ["http://test-site.com/*"],
"js": ["content.js", "jquery-3.1.0.min.js"]
}
],
"permissions": [
"tabs",
"storage",
"http://test-site.com/*"
]
}
and this is content.js file
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.act == "fill"){
let name = request.name;
let email = request.email;
$('#name').val(name);
$('#email').val(email);
}
});
That works perfectly fine on a normal HTML page.
But it doesn't work on a react page.
I guess obvious reason is that things are handled by state and if I can somehow alter the state, I should be able to get it working.
I tried this code ( file = content.js )but no success
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.act == "fill") {
this.setState({"form.name": "My Name"});
}
}.bind(this));
This is the eventPage.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if (request.todo == "showPageAction")
{
chrome.tabs.query({active:true,currentWindow: true}, function(tabs){
chrome.pageAction.show(tabs[0].id);
});
}
});
I am unable to access the state in the extension JS.
What would be the proper way to perform this task?