Javascript Bookmarklet - Download Images - javascript

Edit: Thanks to #Dogoku, I was able to find a solution (here). It turns out that Chrome doesn't allow/handle the download attribute anymore, so we have to force a workaround.
I'm trying to create a javascript bookmarklet that downloads images (code shown below). It's accessing the url correctly, but instead of downloading the image it just opens the image in a new tab.
Please help!
r.addEventListener('click', function(ev) {
r.href = h;
r.download = c;
}, false);
document.body.appendChild(r), r.click(), document.body.removeChild(r);
the variable r is created using document.createElement("a") which creates an element like so:
Before, when using a bookmarklet you could basically just "click" on the image and it would download.

Related

Open or redirect to Base64 DataURL via jQuery or JS

I have a script which converts a canvas element to an <img>tag and then reloads it in a new window (about:blank page). If I then right-click the image and select 'Open Image In New Tab' it opens the Base64 DataURL (i.e. Just the image).
Is there any way to open the Base64 DataURL without the user having to right-click the image?
Ideally, the user would never even see the about:blank page and would simply be redirected to the DataURL.
Here is the current code that generates the image and opens it in a new window:
<script>
function print_card(){
var canvas=document.getElementById("canvas");
var win=window.open();
win.document.write("<img id='compiledImg' src='"+canvas.toDataURL('image/png')+"' width='324' height='204' style='margin: 0; padding: 0; background: #e6e6e6;'/>");
win.location.assign(reload);
}
$("#printCard").click(function(){ print_card(); });
</script>
It seems like I should be able to get the dataURL from the image id and redirect to it as opposed to a new window, but I have no idea how to accomplish it.
I tried assigning canvas.toDataURL('image/png) to win.location but that did not help.
Any guidance would be much appreciated.
It seems that you are simply trying to open the generated image in a new tab. Most modern browsers do not allow opening data URLs programmatically in the top frame for security reasons, you need to use a different method, eg. a blob like this:
function openCanvasContentInNewWindow(canvas) {
canvas.toBlob(blob => {
const objectURL = URL.createObjectURL(blob);
window.open(objectURL);
}, 'image/png');
}
Reference for the HTMLCanvasElement.toBlob method.
If you need to support browsers that do not support HTMLCanvasElement.toBlob() (such as Edge and older browsers), you can use this polyfill. (Since I am not the author of the polyfill, I am not sure whether it would be OK for me to paste the code here directly.)

Save/copy to clipboard image from page by chrome console

For my project I need to copy image (not url, image name. Only data for ability, for example, to paste it to "Microsoft Paint") from page to clipboard by Chrome console.
I tried this:
copy(document.getElementById('someimage'));
but it returns nothing... It only works with text.
If you don't know, then how to download this image by chrome console?
OR
How to make screenshot of the page and copy or download it using Chrome console?
P.s. I can't use any js libraries.
I have explored few things in chrome dev tools
https://homeguides.sfgate.com/stop-air-flow-ceiling-air-diffuser-28867.html - This is the website I am using it for reference.
In Chrome console try the following command
imageurl= document.getElementsByTagName('img')[0].currentSrc;
copy (imageurl);
Note: Here you can change the img [1] array if you want to get different images
Then if you press ctrl + v in your keyboard you could see the image url with https. Please see the above screenshot.
You can perform the ctrl+ v on your new tab to get the image loaded.
or You can try the following method.
Right click the image and click inspect element
You could see some image url. Copy that URL
Open new Tab and paste the URL
If you right click on it you can see "Save Images" option.
Hope it will help you in someway.
As you mentioned you are using Selenium, here's how to save an image with Selenium:
You need to get the image's URL, load it (using ImageIO in this example) and save it. For example, in Java you would do something like this:
try {
driver = new ChromeDriver();
driver.get("http://...");
WebElement img = driver.findElement(By.cssSelector("#selector"));
BufferedImage buffer = ImageIO.read(new URL(img.getAttribute("src")));
ImageIO.write(buffer, "png", new File("image.png"));
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.close();
}
If you want to copy it directly, your class needs to implement java.awt.datatransfer.ClipboardOwner and then you would do something like this:
try {
driver = new ChromeDriver();
driver.get("http://...");
WebElement img = driver.findElement(By.cssSelector("#selector"));
TransferableImage transferable = new TransferableImage(ImageIO.read(new URL(img.getAttribute("src"))));
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(transferable, this );
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.close();
}
Regarding your other questions, here's how to take a screenshot using Chrome DevTools:
There are 3 Capture... commands in Chrome DevTools. Just follow these steps to get to them:
Open DevTools.
Go to the Elements tab and click on the element you want to take the screenshot of.
Press Cmd + P on Mac or Ctrl + P on Windows.
Type > screen. You will get 3 relevant suggestions:
Mobile Capture full size screenshot: Captures the whole page, including the non-visible (out of viewport) area.
Mobile Capture node screenshot: Captures a single node, in this case, the element you clicked in the second step.
Mobile Capture screenshot: Captures the visible area of the page (viewport).
Click on any of them and the screenshot will download automatically.
However, keep in mind this feature doesn't always work fine, especially the Capture node screenshot one, so it might be better to capture the visible area of the page and crop the afterwards.

Save image as jpg with extension

I'm using Backbone and html2canvas.js, this is the code I have so far for transforming a div to canvas and saving it. It works, but it doesn't add the .jpg extension. Because of this, after downloading the image, FF and Chrome first ask me about the program I want to use to open the file and IE just tells me that I don't have the right program and suggests visiting the store.
In FF and Chrome I can see the image when choosing the default Windows picture viewer etc.
What I would like to achieve is to add the .jpg extension so the file opens in the default program right away:
savePicture: function() {
//$(this.el).find('.drag-img').unwrap();
var image = $(this.el).find('#droppable2');
html2canvas(image, {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg");
var frame = document.getElementById("myHideFrame");
if (!frame) {
frame = document.createElement("iframe");
frame.id = "myHideFrame";
document.body.appendChild(frame);
}
frame.src = img.replace(/^data[:]image\/(png|jpg|jpeg)[;]/i, "data:application/octet-stream;");
}
});
},
Sadly, IE8 and above only supports data URIs in CSS, <link>, and <img>. So adding it to a frame as you are doing will not work.
Could you, for IE8 and above, put the data into an <img> and ask the user to right click and save the image?

What is the correct way to load a linked page, execute an event, and then unload it in a Chrome extension?

I have a Chrome extension that allows you to download data from certain sites.
For the past few days, I have attempted to add a feature that will download data from the sites when they are linked from other sites without having to visit the page and click the addon created download button IF the link to the site ends with #ndslink.
I figured out a solution, but it is INCREDIBLY sloppy and I am looking for a better way to implement this.
Here's the behavior:
Site A links Site B with an href ending in #nddownload. The link is clicked.
The extension disables the default action (open a new window), and instead creates an iframe on Site A and loads the linked URL into the frame.
The extension now runs Site B's content script, which specifically looks for #nddownload in the url, and, when found, proceeds to download some data that would normally be downloaded through a manual "Download" button added onto the page via the extension.
Here is my code.
Site B's content script:
var decklist = [];
$('.col-name').each(function(i, el) {
// IRRELEVANT CODE TRIMMMED
}
});
var data = decklist.join("\r\n");
var saveData = (function () {
// IRRELEVANT CODE TRIMMMED
}());
$(document).ready(function(){
var html = $('.t-deck-title').html();
fileName = $('.t-deck-title').text() + '.txt';
//html = html.replace(/hearthstonedeckdl/, '</br><a class="download" href="#download">DOWNLOAD</a>');
$('.t-deck-title').html(html);
if (window.location.href.indexOf("#ndslink") > -1) {
saveData(data, fileName);
}
$(document).on('click', 'a[href="#download"]', function(){
saveData(data, fileName);
});
});
Script loaded on all URLs (incl Site A):
var $jg = jQuery.noConflict();
$jg(document).ready(function(){
$jg('a[href$="#ndslink').click(function(e) {
e.preventDefault();
});
$jg(document).on('click', 'a[href$="#ndslink"]', function(){
//saveData(data, fileName);
var frameurl = $jg(this).text();
$jg('body').prepend('<iframe id="nddownload" />');
$jg("#nddownload").attr("src", frameurl);
//e.preventDefault();
// Send link to background and download.
});
});
I feel as if I am committing a horrible sin by going this route, but being new to Chrome extensions and generally being inexperienced I could not find a proper way to handle this. I've probably also broken my extension 10 different ways while attempting to do this so a real solution would be much appreciated.
I'm also actually unsure how to go about properly destroying the iframe once the saveData function completes.

Javascript: Clicking Link to Download pdf

I am working on a JS program which should open a webpage www.mysite.com & click on a link inside that webpage to download a pdf.
The link to click looks like this:
<a onclick="download();return false;" href="#noWhere">Click to Download</a>
Ordinarily, manually clicking the link, calls the following function to download the pdf:
function download() {
document.forms[0].action = path + "/xxW04_sv_0140Action.do";
document.forms[0].target = "_self";
document.forms[0].submit();
}
My code is simplified javascript code to open the page & click on the "Click to Download" button is this:
<script>
var linkname = "http://www.mysite.com";
var windowname = "window_1"
// Opens a new window
var myWindow = window.open(linkname, windowname ,"width=400,height=600");
//should open a link to download pdf
myWindow.document.getElementById('href = \"#noWhere\"').click();
</script>
So far I can open the webpage "mysite.com" in a seperate window using but for some reason no button clicking is happening and certainly no pdf is downloaded.
Of course if I manually click the "Click to Download" button it downloads.
Can anyone tell me what i'm doing wrong? Why I cannot simulate a click with the above js code?
Or possibly give me some things to try. Any help much appreciated and Than you.
UPDATE:
From the initial answers below, possibly this method is doomed for failure! Can anyone suggest a better way I could be downloading these pdfs?
You'd better use:
<a href="http://www.mysite.com/mypdf.pdf">
This should download that pdf file.
It won't work. The same-origin policy will prevent you from accessing the content of any pages loaded from another domain.
Also, as #kamilkp pointed out, you have to provide the getElementById() function with an id value. You can't just plug any old stuff in there and expect it to work.
Another problem is your reliance on clicks for this to work. What about users that use the tab key to select links and then press Enter to follow the link?

Categories