Extracting and downloading images from a webpage using a chrome extension - javascript

I hate to say it, but I haven't come a long way in terms of developing extension since I starting learning about it a couple hours ago. :(
I apologize in advance if this this thread is a duplicate, but honestly, I'm at the end of my fuse; here's my problem:
I would like to develop an extension for myself to automatically download a list of images from a website called readcomiconline.to
My first issue is that when I use getElementById() it looks exclusively inside my extension pop-up.
My second issue is that I haven't found a way to automatically download several files using Javascript.
Keep in mind that I won't understand any advanced terms regarding extensions, however I do have a pretty solid understanding of Javascript.
Also, use of JQuery is not preferred.
My code:
Manifest.JSON
{
"name": "Comic Downloader",
"options_page": "options.html",
"version": "1.0",
"description": "Build an Extension!",
"permissions": [ "tabs",
"notifications",
"http://*/",
"https://*/", "downloads", "activeTab", "declarativeContent", "storage", "tabs", "<all_urls>"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"manifest_version": 2
}
popup.JS:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
let changeColor = document.getElementById('changeColor');
chrome.storage.sync.get('color', function(data) {
changeColor.style.backgroundColor = data.color;
changeColor.setAttribute('value', data.color);
});
changeColor.onclick = function(element) {
let color = element.target.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
//{code: 'document.getElementById("divImage")'});
{code: 'var filesForDownload = [];
filesForDownload( { path: "/path/file1.txt", name: "file1.txt" } );
filesForDownload( { path: "/path/file2.jpg", name: "file2.jpg" } );
filesForDownload( { path: "/path/file3.png", name: "file3.png" } );
filesForDownload( { path: "/path/file4.txt", name: "file4.txt" } );
$jq(\'input.downloadAll\').click( function( e ){
e.preventDefault();
var temporaryDownloadLink = document.createElement("a");
temporaryDownloadLink.style.display = \'none\';
document.body.appendChild( temporaryDownloadLink );
for( var n = 0; n < filesForDownload.length; n++ ) {
var download = filesForDownload[n];
temporaryDownloadLink.setAttribute( \'href\', download.path );
temporaryDownloadLink.setAttribute( \'download\', download.name );
temporaryDownloadLink.click();
}
document.body.removeChild( temporaryDownloadLink );
}
);'
});
//{code: 'document.body.style.backgroundColor = "' + color + '";'});
});
};

Related

When running a Chrome Extension, how do I make a class available for later script calls?

I'm writing a Chrome Extension that downloads files from a web page.
I want the extension to track which files have already been downloaded.
For the purpose of reasonable code management, I would like the object to exist in its own Javascript file.
How do I make that class definition available to a request to scan the page?
The error message:
Making DL Tracker: undefined
VM1232:4 Uncaught TypeError: window.DLTracker is not a constructor
at processThatPage (<anonymous>:4:17)
at <anonymous>:5:3
The class file (lib/externalclass.js):
window.DLTracker = class DLTracker {
constructor()
{
console.log("constructing the external class");
}
};
The file that's trying to import the class (lib/processpage.js):
export function processThatPage() {
let dltracker;
console.log("Making DL Tracker: " + window.DLTracker);
dltracker = new window.DLTracker();
}
The entry point: automata.js
import { processThatPage } from "./lib/processpage.js";
chrome.runtime.onInstalled.addListener(() => {
chrome.tabs.onUpdated.addListener( pageLoadCheck);
});
async function pageLoadCheck(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.url.startsWith("https://www.target.net/path"))
{
>>>> I'm sure I have to do something here to install the object. This didn't work. What does?
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
files: ["./lib/externalclass.js"]
});
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
func: processThatPage
});
}
}
Just for completeness, the manifest (manifest.json):
{
"name": "My Automator",
"description": "What I'm trying to accomplish",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "automata.js",
"type": "module"
},
"permissions": ["storage", "tabs", "scripting", "downloads", "alarms"],
"host_permissions": ["http://*.target.net/*", "https://*.target.net/*"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
},
"icons": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
},
"options_page": "options.html"
}
Thank you!

Chrome extention with clickablelinks function

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...

Chrome extension: Content script not picking up changes to chrome.storage

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}".`
);
}
});

Chrome Extension failed with chrome.identity.launchWebAuthFlow 'Authorization page could not be loaded.'

I want to authorize with Google after start extension.
I write manifest.json and background.js as below.
current directory structure
manifest.json
{
"manifest_version": 2,
"name": "***************",
"short_name": "DSBOT",
"version": "0.0.1.0",
"description": "**************************",
"icons": {
"16": "images/icon_16.png",
"48": "images/icon_48.png",
"128": "images/icon_128.png"
},
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_icon": {
"19": "images/icon_19.png"
},
"default_popup": "popup.html"
},
"permissions": [
"identity",
"http://*/*",
"https://*/*",
"storage"
],
"oauth2": {
"client_id": **************,
"scopes": ["openid", "email", "profile"],
"hd": "zabuton.co.jp"
}
}
background.js
var clientId = "********************";
var redirectURL = chrome.identity.getRedirectURL();
var url = "https://accounts.google.com/o/oauth2/v2/auth?" +
"scope=email&" +
"response_type=token&" +
"client_id=" + encodeURIComponent(clientId) + "&" +
"redirect_uri=" + encodeURIComponent(redirectURL) + "&" +
"prompt=consent";;
chrome.identity.launchWebAuthFlow({ url: url, interactive: true }, function(redirect_url) {
console.log('redirect_url = ' + redirect_url);
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
After install and run, output log 'Authorization page could not be loaded.'.
redirect_url inside of launchWebAuthFlow is undefined.
If you know my mistake, please teach me.
You don't have the key in your manifest.
You need to copy your extension's key to the manifest.
When you register your application in the Google OAuth console, you'll
provide your application's ID, which will be checked during token
requests. Therefore it's important to have a consistent application ID
during development.
To keep your application ID constant, you need to copy the key in the
installed manifest.json to your source manifest.

Chrome extension that replaces images with other images

how can I do a Chrome extension that replaces images with other images?
Here's my manifest.json code so far:
{
"name": "HaramB",
"version": "69.0.420.666",
"manifest_version": 2,
"description": "This is HaramB's own extension!",
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "popup.html",
"default_title": "HaramB"
},
"permissions": [
"activeTab",
"https://ajax.googleapis.com/"
],
"icons": {
"128": "images/icon.png"
},
"web_accessible_resources": [
"images/nicolas.jpg"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["onPage.js"],
"css": ["onPage.css"]
}]
}
And here's my onPage.js code:
var picture = "images/nicolas.jpg";
document.getElementsByTagName("img").setAttribute("src", picture);
Dont't care about the popup.html or the onPage.css files.
It's the onPage.js file i want it to do it with, if it's not possible, tell me.
document.getElementsByTagName() returns an Array of elements. This means you need to loop through the array and call the methods you want on them individually, like so:
var picture = "images/nicolas.jpg",
images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", picture);
};
Note: it is preferable to use images[i].src = ... to using setAttribute as detailed in this question

Categories

Resources