Commit 764f6b58 authored by crystallambert@chromium.org's avatar crystallambert@chromium.org Committed by Commit Bot

[Extension Docs]Sample Extension

Sample extension that uses a content script to find images on pages,
then displays images in popup.
If user clicks image it will download.
Extension has options page where users can choose to save downloaded images,
download them again, or display them as thumbnails in popup.

This extension may be used in updated debugging tutorial.

Bug: None
Change-Id: I38a2bd5af135ad74b889e8366ae36a08d6d53cb0
Reviewed-on: https://chromium-review.googlesource.com/1053958Reviewed-by: default avatarDevlin <rdevlin.cronin@chromium.org>
Commit-Queue: Crystal Lambert <crystallambert@chromium.org>
Cr-Commit-Position: refs/heads/master@{#568236}
parent 4096750b
// 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';
// Declare extension default properties
let downloadsArray = [];
let initialState = {
'savedImages': downloadsArray,
'thumbnails': false,
'saveImages': true
};
// Set extension setting on installation
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: 'developer.chrome.com', schemes: ['https'] },
css: ['img']
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}]);
});
chrome.storage.local.set(initialState);
});
{
"name": "Download Images",
"description" : "Displays all webpage images and allows user to download",
"version": "1.0",
"manifest_version": 2,
"page_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/download_image16.png",
"32": "/images/download_image32.png",
"48": "/images/download_image48.png",
"128": "/images/download_image128.png"
}
},
"icons": {
"16": "/images/download_image16.png",
"32": "/images/download_image32.png",
"48": "/images/download_image48.png",
"128": "/images/download_image128.png"
},
"permissions": [
"downloads",
"storage",
"activeTab",
"declarativeContent"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"options_page": "options.html"
}
<!DOCTYPE html>
<html>
<head>
<title>Options: Download Images</title>
<style>
#options_div {
margin: 30px;
}
#saved_images {
display: flex;
align-items: center;
justify-content: center;
}
img {
max-width: 100%;
max-height: 100%;
}
.square {
height: 175px;
width: 175px;
margin: 10px;
}
</style>
</head>
<body>
<div id="options_div">
<input type="checkbox" id="thumbnails"> Display Images as Thumbnails
<br />
<br />
<input type="checkbox" id="save_images"> Save Downloaded Images
<br />
<br />
<button id="delete_button">Delete Saved Images</button>
</div>
<div id="savedImages"></div>
<script src="options.js"></script>
</body>
</html>
// 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'
// Selects saveImagesOption checkbox element
let saveImagesOption = document.getElementById('save_images');
// Selects thumbnailOption checkbox element
let thumbnailOption = document.getElementById('thumbnails');
function setCheckbox(data, checkbox) {
checkbox.checked = data;
};
// Gets thumbnails and saveImages value from storage
chrome.storage.local.get(['saveImages', 'thumbnails'], function(data) {
setCheckbox(data.saveImages, saveImagesOption);
saveImagesOption.checked = data.saveImages === true;
setCheckbox(data.thumbnails, thumbnailOption);
});
// Saves users prefrences
function storeOption(optionName, optionValue) {
let data = {};
data[optionName] = optionValue;
chrome.storage.local.set(data);
};
saveImagesOption.onchange = function() {
storeOption('saveImages', saveImagesOption.checked);
};
thumbnailOption.onchange = function() {
storeOption('thumbnails', thumbnailOption.checked);
};
let savedImages = document.getElementById('savedImages');
let deleteButton = document.getElementById('delete_button');
deleteButton.onclick = function() {
let blankArray = [];
chrome.storage.local.set({'savedImages': blankArray});
location.reload();
};
// Gets saved downloaded images from storage
chrome.storage.local.get('savedImages', function(element) {
let pageImages = element.savedImages;
pageImages.forEach(function(image) {
// Create div element and give it class of square
let newDiv = document.createElement('div');
newDiv.className = 'square';
// Create image element
let newImage = document.createElement('img');
// let lineBreak = document.createElement('br');
// Image source is equal to saved download image
newImage.src = image;
newImage.addEventListener('click', function() {
chrome.downloads.download({url: newImage.src});
});
// Append all elements to options page
newDiv.appendChild(newImage);
savedImages.appendChild(newDiv);
});
});
<!DOCTYPE html>
<html>
<head>
<title>Download Images</title>
<style>
body {
min-width: 300px;
font-size: 15px;
}
input {
margin: 5px;
outline: none;
}
img {
max-width: 100%;
max-height: 100%;
}
.square {
height: 175px;
width: 175px;
margin: 10px;
}
</style>
</head>
<body>
<h1>Click image to download.</h1>
<button id="options_button">Options</button>
<br>
<div id="image_div"></div>
<script src="popup.js"></script>
</body>
</html>
// 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'
// Script code to inject on page
// Selects images then returns array of their currentSrc
const scriptCode =
`(function() {
let images = document.querySelectorAll('img');
let srcArray =
Array.from(images).map(function(image) {
return image.currentSrc;
});
return srcArray
})();`;
// Declare add image function to save downloaded images
function addImage(url) {
chrome.storage.local.get('savedImages', function(result) {
// Check if storage has exsisting arrays
// If array found, blank array is replaced with found array
// If no array, we add to created blank array
let downloadsArray = result.savedImages || [];
// Images are added
downloadsArray.push(url);
// Chrome stores the new array with the new image
chrome.storage.local.set({'savedImages': downloadsArray}, function() {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
console.log('Image saved successfully');
};
});
});
};
// Grabs the imageDiv from the popup
let imageDiv = document.getElementById('image_div');
function setUp(array) {
chrome.storage.local.get(
['saveImages', 'thumbnails'], function(config) {
for (let src of array) {
let newImage = document.createElement('img');
let lineBreak = document.createElement('br');
newImage.src = src;
console.log(newImage)
// Add an onclick event listener
newImage.addEventListener('click', function() {
// Downloads and image when it is clicked on
chrome.downloads.download({url: newImage.src});
// Checks if extension is set to store images
if (config.saveImages === true) {
// If true, call addImage function
addImage(newImage.src);
};
});
// Checks extension thumbnail settings
if (config.thumbnails === true) {
// If on, popup displays images as thumnails
let newDiv = document.createElement('div');
newDiv.className = 'square';
newDiv.appendChild(newImage);
imageDiv.appendChild(newDiv);
} else {
// If off, images are displayed at full size
imageDiv.appendChild(newImage);
};
imageDiv.appendChild(lineBreak);
};
});
};
// Runs script when popup is opened
chrome.tabs.executeScript({code: scriptCode}, function(result) {
setUp(result[0]);
});
let optionsButton = document.getElementById('options_button');
optionsButton.onclick = function() {
chrome.tabs.create({ url: "options.html" });
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment