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.
Related
EDIT
The source of this problem is the behavior of the Edge browser, as identified by Sami. Firefox does the same thing, but Chrome works fine.
Original Question
I have a drop container for users to drag and drop an image to set an <input type="file"> with the image.
If the image is being dragged and dropped from a different page, the image is recognized as a file. However, if the image is dragged and dropped from the same page with the drop container, it is recognized as a URL.
Why isn't the image being recognized as a file when it is dragged and dropped from the same page as the drop container?
Here is the fiddle with the drop container and image file. When you drag the image file on this page into the drop container, it is recognized as a URL although I want it to be recognized as a file.
https://jsfiddle.net/nadf9c82/1/
Next, try dragging the image on this fiddle https://jsfiddle.net/7sqb5r0f/1/ into the drop container on the other fiddle and you will see it is recognized as a file, which is what I want.
Why do images on the same page as the drop container evaluate as URLs and not files? Is there a fix to make them recognized as files and not URLs?
Here is the code for reference
<div class="dropContainer" id="dropContainer">Drop Here</div>
<div id="imagetwo">
<img src="http://a.mktgcdn.com/p/khxNbcdQcr1HQKNgk9cPNUyWUprmZ5Dryx9P5MAV0SE/2669x3840.jpg" />
</div>
<script>
dropContainer.ondrop = function(evt) {
//evt.preventDefault();
if(evt.dataTransfer.files[0]){
console.log("is a file");
const dT = new DataTransfer();
dT.items.add(evt.dataTransfer.files[0]);
fileInput.files = dT.files;
}else{
// Try dataTransfer url second
var dataTransferUrl = evt.dataTransfer.getData('url');
if(dataTransferUrl){
console.log('is a url, not a file');
console.log(dataTransferUrl);
}
}
};
</script>
I think you can do it, but it won't work in Fiddle due to The page at 'https://jsfiddle.net/' was loaded over HTTPS, but requested an insecure resource ... the content must be served over HTTPS due to your HTTP request
Here's what I think, whenever you drop the image, it'll receive an URL instead of the file like you want. Then just make it into a file.
It's called convert your URL image to File object, if my way is not working, it's the keyword for you to have a look more, I hope it'll give you some ways to work around since I'm not good at this, too.
Replace this code of mine into your Try dataTransfer URL second part, but be warned that it'll fire an error on Fiddle due to HTTP request. So I've to replace the HTTP with HTTPS, but it'll get you the CORS Block, so if you have the extension to unblock CORS, it'll work, for development or testing purposes, of course.
let url = evt.dataTransfer.getData('url');
const urlArray = Array.from(url)
urlArray.splice(4, 0, 's')
const urlFinal = urlArray.join('')
fetch(urlFinal)
.then(async (res) => {
const contentType = await res.headers.get('Content-Type')
const blob = await response.blob()
const file = new File([blob], "image.jpeg", { contentType })
})
}
When I drop an image to Drop Here box, it'll create an Object File, so it'll count as a file instead of an URL, I think that's what you want, hope I can help you somehow.
Take an URL as an Object File after Dragging Image and Drop it into Drop Here Box
I would like to hover my mouse on a URL and copy the URL with CTRL+Alt+C. This topic pretty much describes 99% of what I'm trying to do:
https://www.autohotkey.com/board/topic/111762-mouse-hover-copy-link/?p=662644
I've taken the userscript and modified it slightly, so that it gives me the URL after the "href" part. By the way, I'm not at all proficient with Javascript, I've simply played around with it and was lucky to get it working. Here's what I have:
This works great, but this copies the URL everytime I hover my mouse on a link. I don't want this, as it just adds a bunch of URLs to my clipboard.
At the bottom of that post, there's a Autohotkey component. It gets the tab title, rather than the URL.
How can I modify both the userscript and the Autohotkey to do what I want?
As a secondary question - I would like to create an additional userscript using the Javascript above as a reference. This new userscript will take the URL that my mouse is hovering on, change it so that it is prefixed with word:ofe|u| and pastes that into the URL bar when I click on the link while holding the Alt key. So basically:
Hover mouse on a URL that I am interested in (e.g. https www.google.com)
Userscript will modify the URL and change it to word:ofe|u|https://www.google.com
Hold down Alt + left click on the URL
word:ofe|u|https://www.google.com - page is loaded, or URL is pasted into the URL bar
UPDATE:
I've managed to get something going, not sure how I did it but I just played around with the codes I found on Google. Again, I do not know anything about Javascript.
https://pastebin.com/S9znPxBU
// ...
This works well, but if you do single press of CTRL+C, it just keeps copying URLs to the clipboard whenever you hover your mouse on a link. I want it to only start copying a URL to the clipboard everytime I press CTRL+C.
AutoHotkey won't help much here, as it can't access the URL directly. Thankfully, you can use the new JavaScript Clipboard API. It only works in secure contexts (AKA HTTPS) and the page needs to be in focus. Doing this using a browser extension would be perferred, since it can workaround those restrictions.
Try it, but first click on a blank area in the preview window to focus it.
// Userscript
"use strict";
window.addEventListener("load", () => {
const evOpts = {capture: true, passive: true};
let hoveredLink = null;
for (let link of document.getElementsByTagName("a")) {
link.addEventListener("mouseenter", () => {
hoveredLink = link;
}, evOpts);
link.addEventListener("mouseleave", () => {
hoveredLink = null;
}, evOpts);
}
window.addEventListener("keydown", (ev) => {
if (hoveredLink && ev.ctrlKey && ev.altKey && ev.code === "KeyC") // Ctrl+Alt+C
// Copy *absolute* URL to the clipboard
navigator.clipboard.writeText(new URL(hoveredLink.href, location.href)).then(()=>{
console.log("URL copied to clipboard!");
}, (err)=>{
console.error("Error copying URL to clipboard: ", err);
});
}, evOpts);
});
Google Youtube
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.
I am doing:
driver = new webdriver.Builder()
.forBrowser('safari')
.build();
var referrer = 'http://localhost:3000/tours/hood-river';
// console.log(referrer);
driver.get(referrer);
driver.findElement(By.id('requestGroupRate')).click();
//requestGroupRate is a link, so clicking it should move it to a new page
driver.wait(function(){
return driver.findElement(By.id('myThing')).then(function(element){
console.log("hereere");
assert(element.value === referrer);
done();
});
},10000);
I find that the findElement(By.id('myThing')), fails, even though the page it should be on clearly has 'myThing'. But if I change the line to
driver.findElement(By.id('requestGroupRate'))..
Then the element is found! This leads me to believe, that the click() does not cause the driver to navigate to the link.
EDIT: The link I am trying to click on:
<a id="requestGroupRate"
href="/tours/request-group-rate">Request Group Rate.</a>
you can simply add driver.sleep(10000) after click() for debug purpose.
if the page changed, means the link and click() worked and the possible failed reason it's when script click on the link, the page is still loading, so browser failed to response to the click event.
then you can move the driver.sleep(10000) after browser.get() to see click() can work or not.
As suggested by acdcjunior findout if element is clickable use browser developer tools. Chrome it is a side panel, Firefox it is a marker at the end of the HTML tag.
I have had issues getting Selenium to click on a GIS map. In that case i use an alternative (will need to translate this Java into Javascript):
((JavascriptExecutor) driver).executeScript("document.getElementById('map_container').dispatchEvent(new Event('click'));");
Also suggest testing your xpath in the browser developer console:
document.evaluate(".//tagName[#id='Query']", document,null, XPathResult.ANY_TYPE, null).iterateNext();
Or testing your cssSelector in the browser developer console:
document.querySelector('#idtext')
i'm currently working on a function (started after Buttonclick) to print a document in Lotus Notes (IBM Domino Designer 9.0 Social Edition Release 9.0). I have a custom control which creates a new document to the database. After saving the document its opened in read-only-Mode. There you have a button which will redirect you to a new window where the same contents are displayed without any layouts and something else (just the Text). Now its possible to print the page with Ctrl+P. There are two differen xPages for that.
Distribution.xsp
DistributionPrint.xsp
First of all i'm using
path = facesContext.getExternalContext().getRequest().getRequestURL();
to get the current page URL. After that there is an option to replace the current Page of the path (Distribution.xsp) into DistributionPrint.xsp.
var replacePage = #RightBack(path, "/");
path = #ReplaceSubstring(path, replacePage, "DistributionPrint.xsp");
When im testing it the replacement successfully worked. After that i'm bulding a new URL for the specific document to open with the new path. Finally everything is placed into the view.postScript method:
var docid = docApplication.getDocument().getUniversalID();
view.postScript("window.open('"+path.toString() + "?documentId=" + docid + "&action=openDocument"+"')")
Now my Problem starts. At 99% of my trys the new window is opened like i said the programm to do. But there are some kind of documents where i click on the button and he doesn't open a new window and trys to open the old Distribution.xsp url. I already tested out the path he wants to open at these kind of documents by using the debugtoolbar. The result of the button click returns the completly correct URL which should be opened. I can also copy that url and paste it manually into my browser => it works! But if i want to open that URL by a buttonclick and viewPostScript nothing happens.
Has anybody expierenced the same problem like me? Maybe one of you can help me through that problem. Its really annoying that everything works finde at 99% of my documents but at some documents it doesn't work although the given url is 100 percent correct.
Thanks for everyones help!
Try adding you code into a javascript function on the page and call that function from your view.postscript code
Or as Panu suggested add it to onCompete code
If the URL is correct then it sounds like a problem with view.postScript. Try with <xp:this.onComplete>.
Other things to try:
Use var w = window.open(... Plain window.open may change the URL of
current window.
Double check the URL with an alert();
You might be barking up the completely wrong tree. Did you try, instead of creating a second page for printing, create a second CSS stylesheet?
Using #Media Print you can tell the browser to use that stylesheet for printing. There you set all navigational elements to display : none and they won't print.
Removes the need to maintain a separate XPage for the printing stuff.
Thank you everyone for your suggestions. The solution of Fredrik Norling worked for me. I placed the Code into a function and called it at the buttonclick. Now every page is opened as expected. Thank you very much for the help!