Creating An Image Download Chrome Extension - image

I am creating a chrome extension that downloads all the images on the current webpage and this is what I have
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
downloadImages()
}, false);
}, false);
function downloadImages() {
var images = document.getElementsByTagName('img');
var srcList = [];
var i = 0;
setInterval(function(){
if(images.length > i){
srcList.push(images[i].src);
var link = document.createElement("a");
link.id=i;
link.download = images[i].src;
link.href = images[i].src;
link.click();
i++;
}
},1500);
}
This adds a click listener that should download all images when you click the button on the other section. I know this code works because I replaced the code that downloads the images with the code for an alert and when I pressed the button it indeed made an alert, so why is it that when I add the image downloading code it doesn't do anything? Also I have tested the image downloading code, it works.

Related

Unable to download file with CasperJS

I am trying to download a file with CasperJS. If using browser, the download begins when user clicks a button and the response headers look like this:
I have tried these two methods with no luck:
1) https://stackoverflow.com/a/26334034
With this approach, the code block inside the if-statement is never executed. If I remove the condition, a bunch of resources are being saved, such as css files and so on. So the event listener is working, but for some reason not triggering when I use CasperJs click function to click the button that should start the download.
2) https://stackoverflow.com/a/30122021/692695
File.csv is saved but it's the web sites sourcecode, not the csv-file I get when I click the button on the website.
All of my code:
'use strict';
var utils = require('utils');
var casper = require('casper').create({
//verbose: true,
//logLevel: "debug",
clientScripts: ["node_modules/jquery/dist/jquery.min.js"]
});
function writeHtml(filename) {
var fs = require('fs');
var content = casper.getHTML();
fs.write(filename, content, 'w');
}
function getUrl() {
var url;
url = $('.tableofcontent_link:contains("Väestö työmarkkina-aseman, sukupuolen ja iän mukaan")').parent().attr('href');
return url;
}
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
var link;
var url = 'http://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__tym__tyti/?table';
casper.start(url);
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');
casper.then(function () {
this.echo("Now at: " + this.getCurrentUrl());
link = 'http://pxnet2.stat.fi' + casper.evaluate(getUrl);
});
casper.then(function () {
this.open(link);
});
casper.then(function() {
this.echo("Now at: " + this.getCurrentUrl());
// Select all data for each item
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl01_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl02_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl03_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl04_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl05_VariableValueSelect_VariableValueSelect_SelectAllButton');
});
casper.then(function() {
// casper.selectOptionByValue('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_OutputFormats_OutputFormats_OutputFormatDropDownList',
// 'FileTypeExcelX');
// Select the format of the file from the select option list at the bottom
casper.selectOptionByValue('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_OutputFormats_OutputFormats_OutputFormatDropDownList',
'FileTypeCsvWithHeadingAndSemiColon');
});
casper.then(function () {
// just for debugging
writeHtml('page1.html');
});
casper.then(function() {
//casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_ButtonViewTable');
});
casper.then(function() {
// FIRST ATTEMPT TO LOAD THE DATA TO a file called file.csv
var formData = casper.evaluate(function(){
return $('form#aspnetForm').serialize();
});
//this.echo("Params: " + formData);
var targetFile = 'file.csv';
casper.download(link, targetFile, 'POST', formData);
});
casper.then(function () {
// just for debugging
writeHtml('page2.html');
});
// SECCOND ATTEMPT TO LOAD THE DATA TO a file called stats.csv
casper.on('resource.received', function (resource) {
if ((resource.url.indexOf('tyti_001') !== -1) ) {
this.echo(resource.url);
var file;
file = "stats.csv";
try {
this.echo("Attempting to download file " + file);
var fs = require('fs');
casper.download(resource.url, fs.workingDirectory + '/' + file);
} catch (e) {
this.echo(e);
}
}
});
casper.run(function () {
this.echo('End').exit();
});
And my package.json:
{
"scripts": {
"test": "dotest"
},
"pre-commit": ["test"],
"dependencies": {
"jquery": "^3.3.1"
},
"devDependencies": {
"pre-commit": "^1.2.2"
}
}
Explanation of the code:
First visit this page: http://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__tym__tyti/statfin_tyti_pxt_001.px/?rxid=bd4d5dc1-358d-407e-ae47-13266b79bfd0
There, dynamically pick a specified link and move there.
Select all data by clicking the V-shapen icon (look at the attached screenshot) and then select the format of the file.
I've faced this issue earlier with all versions except phantomjs 2.0.0. I also tried the solutions you shared from SO a year ago and they didn't work as well.
I'm going to assume you're using a phantomjs version other than 2.0.0.
Here's the link to download it
https://bitbucket.org/ariya/phantomjs/downloads/
With it, you will have access to onFileDownload method which you can override and use like below
casper.page.onFileDownload = function(status){
console.log('onFileDownload(' + status + ')');
return "newfile.csv";
};
onFileDownload will be called whenever a file is downloaded as a result of clicking a button (ajax) or as a result of sequential get/post requests.
All you have to do is, trigger the click on the button/link that will initiate download.
Note : My solution is assuming that everything else (site is not blocking phantomjs and your request headers/cookies are as expected)

To access the text area in the html rendered using Iframe which itself is loaded withing a cshtml page

I have an iframe loaded within a Cshtml page. The Iframe contains an html form. i need to add an image in front of each text area of the form when the main page(cshtml page) is loaded. Have tried a lot of things but nothing has worked as such. Below is the code i am trying:
$("#iframe").ready(function() {
$.each($('input[type=text],textarea'), function() {
var idOfCurrentElement = $(this).attr('id');
var classNameOfCurrentElement = $(this).attr('class');
var visibilityOfCurrentElement = $(this).css('visibility');
if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
$("<img src='~/images/pic' alt='Pic'>");
});
});
You must access iframe content, not your page.
$("#iframe").ready(function() {
$.each($('#iframe').contents().find('input[type=text],textarea'), function() {
var $thatButton = $(this);
var idOfCurrentElement = thatButton .attr('id');
var classNameOfCurrentElement = thatButton ).attr('class');
var visibilityOfCurrentElement = thatButton .css('visibility');
if(classNameOfCurrentElement != "hidden" && visibilityOfCurrentElement == "visible")
//do what you want.
});
});

Dropzone sailsjs nodejs upload image NetworkError: 404 Not Found

I use Sails.js, which is based on Node.js. For the upload I use Dropzone. To display the pictures I use owl-carousel.
When I add a new picture and I try to display it I receive the following error:
"NetworkError: 404 Not Found - http://localhost:1337/superrare/b004421de079bb2531cc5cd6346d202d/dde8221dc9e0b750479cedd3924af191/dde8221dc9e0b750479cedd3924af191.png"
If I open the above link in another tab I can see the image, because it exists at the specific path.
If I refresh the page I can see the picture in the owl carousel, with the same path that is displayed above.
If I modify the Dropzone code for testing purposes, on success add to carousel an older picture, the picture will be displayed -> imagePath = '/superrare/b004421de079bb2531cc5cd6346d202d/d845a68e5a57acf2f879bcd50966cc11/d845a68e5a57acf2f879bcd50966cc11.png';
So only when I try to add a new picture path I receive a 404 error...
If I add a delay of 5 seconds, the error is the same 404.
Here is my code
Dropzone.options.mydropzone = {
autoProcessQueue: false,
init: function () {
var imageName, imagePath, imageID;
var submitButton = document.querySelector("#submit-all");
myDropzone = this; // closure
this.on("success", function (file, responseJson) {
imageName = responseJson.createdAt;
imagePath = responseJson.path;
//imagePath = '/superrare/b004421de079bb2531cc5cd6346d202d/d845a68e5a57acf2f879bcd50966cc11/d845a68e5a57acf2f879bcd50966cc11.png';
imageID = responseJson.id;
var content = '<div class="item"><div id="visinput" class="container-img">'+
'<img file-id="' + imageID + '" src="' + imagePath + '">'+
'</div></div>';
// get owl element
var owl = $("#owlUpload");
// add item to owl carousel
setTimeout(function () {
owl.data('owlCarousel').addItem(content);
}, 5000);
document.getElementById("serverFile").value = fileProcess;
});
},
paramName: "file",
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};

how to append iframe to hosted page using Firefox SDK addon?

Assume frame.html inside data folder in Firefox SDK addon,
how to append an iframe and define frame.html as its source?
Additional info:
Because of CPS, its not possible to use inline source, so I can't use data.load('frame.html'), I need to use URL of the file:
lib/main.js
tabs.activeTab.attach({
contentScriptFile: [self.data.url("js/appender.js") ],
attachTo: 'top',
contentScriptOptions: {
scriptUrl: self.data.url("js/sandbox.js"),
imageUrl: self.data.url("image.jpg")
frameUrl: self.data.url("sandbox.html")
}
});
data/appender.js
var scriptTag = document.createElement("script");
scriptTag.src = self.options.scriptUrl;
document.body.appendChild(scriptTag); // worked fine
var imageTag = document.createElement("image");
imageTag.src = self.options.imageUrl;
document.body.appendChild(imageTag); // worked fine
var iframeTag = document.createElement("iframe");
iframeTag.src = self.options.frameUrl;
document.body.appendChild(iframeTag); // the html tag of iframe is empty
It's blank because of the firefox security policy which doens't allow content scripts to load resources URLs as iframes. The solution could be to set it directly from the background script, for this you'll need to use low level sdk.
var { viewFor } = require("sdk/view/core");
var tab_utils = require("sdk/tabs/utils");
var iframe = viewFor(tab).linkedBrowser._contentWindow.document.querySelector('iframe[src="' + self.data.url("sandbox.html") + '"]')
iframe.contentWindow.location.href = iframe.getAttribute("src")
so the completely working code would look like:
data/appender.js
var iframeTag = document.createElement("iframe");
iframeTag.src = self.options.frameUrl;
document.body.appendChild(iframeTag); // the html tag of iframe is empty
// note that the iframe is attached after the content ready event, so you have to inform the background when it can start working with the iframe
self.port.emit("attached", true);
main.js
tabs = require("sdk/tabs")
self = require("sdk/self")
var { viewFor } = require("sdk/view/core");
tab_utils = require("sdk/tabs/utils");
tabs.on("ready", function(tab) {
var worker = tab.attach({
contentScriptFile: [self.data.url("js/appender.js") ],
attachTo: 'top',
contentScriptOptions: {
frameUrl: self.data.url("sandbox.html")
}
});
worker.port.on('attached', function() {
reinitIframe(tab)
});
function reinitIframe(tab) {
var iframe = viewFor(tab).linkedBrowser._contentWindow.document.querySelector('iframe[src="' + self.data.url("sandbox.html") + '"]')
iframe.contentWindow.location.href = iframe.getAttribute("src")
}
})
You'll probably need a cross-process wrapper in order to make it work in future version of Firefox with electrolysis
Found a better way. You add a blank <iframe> and attach an event listener for the load event. Then you can easily append whatever elements you want to the iframe as usual.
Include this in your content-script:
var iframe = document.createElement('iframe'),
div = document.createElement('div');
div.textContent('Hello World');
document.body.appendChild(iframe);
iframe.addEventListener('load', function(){
this.contentWindow.document.body.appendChild(div)
})

How to add button in toolbar of print preview fire fox using add SDK

How to add button in toolbar of print preview fire fox using add SDK.
thank you so much
function addToolbarButton() {
var {Cc, Ci, Cu} = require("chrome");
var mediator = Cc['#mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
var document = mediator.getMostRecentWindow("navigator:browser").document;
var navBar = document.getElementById("print-preview-toolbar");
if (!navBar) {
return;
}
var btn = document.createElement("toolbarbutton");
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'toolbarbutton-1');
btn.setAttribute('image', data.url('print-on_small.png')); // path is relative to data folder
btn.setAttribute('orient', 'horizontal');
btn.setAttribute('label', ' In');
btn.addEventListener('click', function() {
console.log('clicked');
}, false)
navBar.appendChild(btn);
}

Resources