Is there any way to insert image using "prompt()" in JavaScript? - javascript

I want to insert an image using prompt() in JavaScript
Here is the thing I tried :
var name = prompt("Enter your name"); [Typeof string or number]
What I want is:
var profile_img = prompt("Choose Your Picture"); [Typeof img]

No, it is not possible. A window.prompt() call only accepts text input.
Depending on your use case, the user could enter the public URL to an image (any supported protocol, even the pseude-scheme data:) and your script could then fetch the image from the given URL. Another possibility mentioned by Andrew in the comments: have users input an encoded version of the image (base64, hexdump, …) and then parse it yourself to get back the binary image data.
To then insert the image into your DOM, see other questions and answers on Stackoverflow, such as DOM appendChild to insert images:
let img = document.createElement("img");
img.src = 'path/to/image';
parent_element.appendChild(img);

What you can do is to use <input type="file" .. and trigger it with the js
Assuming you have jQuery, but the principle should work regardless
<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />
Then look at this answer how to display the image without uploading it to the server

Related

js assign one image input value to another

I have two image input fields
<input type="file" accept="image/*" id="one" />
<input type="file" accept="image/*" id="two" />
I am trying to sync value from two to one, whenever two receives input, assign the value to one. two is just a field visible in frontend, one is the original form used for data collection and upload.
two.onchange = () => {one.value = two.value}
since it is file field, I wonder if this may not work (have not write unit test yet, because even the value is logged in fronted, I doubt the file will be catched in backend). I will be more than grateful if someone suggest a tangible way to do it.
You are doing wrong you have to set .files property instead of .value because the Browser stored files in files property not in value property. You can do it like below Example:
const one = document.getElementById('one');
const two = document.getElementById('two');
two.onchange = () => {one.files = two.files}
<input type="file" accept="image/*" id="one" />
<input type="file" accept="image/*" id="two" />
sorry, #Abdul Basit's answer won't work. I tried to assign files but it turns out working in frontend, but there is actually no data transferred to backend. therefore, it is impossible to assign value(files) between file inputs.
one.files = two.files
<MultiValueDict: {}>
I did it by DOM replacement.
// replace image input
two.remove();
Array.from(one.attributes).forEach(attr => {
two.setAttribute(attr.nodeName, attr.nodeValue);
});
one.parentNode.replaceChild(two, one);
<MultiValueDict: {'image': [<InMemoryUploadedFile: main.jpg (image/jpeg)>]}>
here we got files in backend eventually.

How to get Image tags from html using JavaScript having alt=checked?

There is an image tag in my website as shown below. There are multiple image tags and some have alt="checked" and some have alt="unchecked". All image tags are followed by <input type="hidden"> as shown
<img src="./images/checked.gif" alt="checked" onClick="javascript:methodname('param1','param2','1234')" />
<input type="hidden" id="1234" name="1234" value="check" displayname="displyname" pcID="4704.51127.28929.4371" />
I need to get all the values (either from name or id or parameter of the JavaScript, anything would be fine) for those images which have alt="checked".
You can get all the image elements with alt=“checked” with var images = document.querySelectorAll('img[alt="checked"]');. Then, you can get the ids and whatever other attributes you want using
for (let image of images) {
let id = image.getAttribute('id');
// Do stuff
}

Displaying user uploaded html content - Security Issue

I have a feature where user can upload html file which I then read its content via PHP and send it to the third party API as a string. Now before I send it to the API I want to generate a preview of the HTML they uploaded to the user so they can press Confirm button to send it.
The HTML files should be mostly letter templates but users can modify the html and add some script tags or inject other malicious code that might harm my website while displaying for preview. Is there a way I can avoid this?
I thought about stripping tags but what if they have onclick events within html elements?
Id start with something like this to strip scripts and comments:
$htmlblacklist[] = '#<script[^>]*?>.*?</script>#si'; //bye bye javascript
$htmlblacklist[] = '#<![\s\S]*?--[ \t\n\r]*>#'; //goodbye comments
//now apply blacklist
$value = preg_replace($htmlblacklist, '', $value);
For inline events, you should use DOMDocument, as it understands HTML whereas Regex is shooting in the dark.
In reality, you could use DOMDocument for all of it, and not use Regex at all. Load up the HTML in a DOMDocument object, and iterate through the tree, removing what you want.
Not 100% this will work for you, but it seems that rendering the HTML as an SVG onto a canvas will restrict the contents to within your requirements (no scripts, no loading outside sources).
See more documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
You might wonder how this can be secure, in light of concerns about
the possibility of reading sensitive data out of the canvas. The
answer is this: this solution relies on the fact that the
implementation of SVG images is very restrictive. SVG images aren't
allowed to load any external resources, for example, even ones that
appear to be from the same domain. Resources such as raster images
(such as JPEG images) or s have to be inlined as data: URIs.
In addition, you can't include script in an SVG image, so there's no
risk of access to the DOM from other scripts, and DOM elements in SVG
images can't receive input events, so there's no way to load
privileged information into a form control (such as a full path into a
file element) and render it, then pull that information out by
reading the pixels.
I may have found the library that handles this. Have not yet fully tested it but based on its description it might be the one: http://htmlpurifier.org/
Use a FileReader to read the contents of the file, and an iframe to safely (or not) view it:
document.querySelector("button").addEventListener(
'click',
function() {
let iframe = document.createElement("iframe"),
holder = document.querySelector("#iframeholder"),
sandboxFlags = [
...document.querySelectorAll('.sandbox-flags:checked')
].map(_ => _.value).join(','),
file = document.querySelector('input[type=file]').files[0],
reader = new FileReader();
reader.addEventListener("load", function() {
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("srcdoc", this.result);
/*
* Sandboxing is not allowed in code snippets
* iframe.setAttribute("sandbox", sandboxFlags);
*
*/
console.log(`sandbox=${sandboxFlags}`);
while (holder.firstChild)
holder.removeChild(holder.firstChild);
holder.appendChild(iframe);
}, false);
reader.readAsText(file);
},
false);
label {
display: block
}
#iframeholder>iframe {
border:1px solid black;
height:400px;
width:400px;
}
<div>
<input id="browse" type="file" >
</div>
<label>
<input type="checkbox" class="sandbox-flags" value='allow-script' />allow-scripts
</label>
<label>
<input type="checkbox" class="sandbox-flags" value='allow-popups-to-escape-sandbox' />allow-popups-to-escape-sandbox
</label>
<label>
<input type="checkbox" class="sandbox-flags" value='allow-forms' />allow-forms
</label>
<label>
<input type="checkbox" class="sandbox-flags" value='allow-modals' />allow-modals
</label>
<div>
<button type="button">Preview</button>
</div>
<div id="iframeholder"></div>

How to copy file path in to span in addition to the input control itself?

So far I tried this:
JS:
function Copy(copyfrom, copyto) {
document.getElementById(copyto).value = copyfrom.value;
}
And HTML code look like this:
<div>
<input type="file" onchange="Copy(this, 'txtFileName');" />
</div>
<div>
<span id="txtFileName" type="text" readonly="readonly" />
</div>
I want To copy the selected file name/path to different span,
Thanks!
From Joe Enos answer you don't need to get server path
Some browsers have a security feature that prevents javascript from
knowing your file's local full path. It makes sense - as a client, you
don't want the server to know your local machine's filesystem. It
would be nice if all browsers did this.
And to get the name of file, try to use innerText property of span instead of value as value works on form element fields try this,
function Copy(copyfrom, copyto) {
document.getElementById(copyto).innerText = copyfrom.value;
}
Working demo
<input type="file"..> will not show textbox in chrome and safri browser, you can configure the display styles by CSS itself, go to the link here
This is not possible due to security reasons.
For more details, see: How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

how to get hidden values in webdriver using javascript

There's a hidden input field in which I'm trying to insert a specific date value. The field originally produces a value, from which a user can select an appropriate value.
The page's source code looks like this:
<div id="change_img">
<img width="80" height="30" border="1" src="http://jntuh.ac.in/results/images/CaptchaSecurityImages.php?width=100&height=50&characters=5&code=ryyrh">
<br>
<input id="code" type="hidden" value="ryyrh" name="code">
</div>
Use WebElement's getAttribute method. In your case it will be:
WebElement hiddenInput = driver.findElement(By.id("code"));
String value = hiddenInput.getAttribute("value");
If for any reason you need to do it with javascript (your question specifically asked for js) then this code should work:
String script = "return document.getElementById('code').getAttribute('value');";
String value = ((JavascriptExecutor) driver).executeScript(script).toString();
I tested this solution in C# and it works. I am then able to parse the returned string to find and verify what I need.
http://yizeng.me/2014/04/08/get-text-from-hidden-elements-using-selenium-webdriver/
So in the example in the question you would get the innerHTML of the visible parent "change_img" element which will include the hidden element.
Solution in Python:
script = "return document.getElementById('code').getAttribute('value');";
print(driver.execute_script(script))
Solution in C#:
string script = "return document.getElementById('code').getAttribute('value');";
string value = ((IJavaScriptExecutor)driver).ExecuteScript(script).ToString();

Categories

Resources