click to direct download with javascript - javascript

I tried the dom-to-image library to download a set of HTML div. The "to-image" part worked just fine, but after the div was converted to an image, I want it also downloaded directly as an image. But I can't do that.
The dom-to-image docs said you can create an anchor element, and put the attributes there, and activate with the click() function:
let link = document.createElement('a');
link.download = 'my-image-name.png';
link.href = dataUrl;
link.click();
here is the example I made with svelte, it won't download, if I put the anchor as a child, I can't click the link. BUT, I can right-click and open in new tab or open image in new tab and also save image as. So I think there's no problem with the src/URL.
<script>
import domtoimage from 'dom-to-image'
let capture, display = false
function close() {
display = !display
document.querySelector(".image").remove()
}
function save() {
console.log("save")
display = !display
domtoimage.toPng(capture)
.then(function (dataUrl) {
let link = document.createElement('a');
link.download = 'my-image-name.jpeg';
link.href = dataUrl;
link.click(); //not working
let img = new Image();
img.src = dataUrl;
img.className = "image"
let show = document.querySelector(".show")
show.appendChild(link).appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
//no error logged
});
}
</script>
<div class="capture" bind:this={capture}>
<h1 >Hello World!</h1>
<p>
<!-- long text just for example -->
</p>
</div>
<button on:click={save}>
save
</button>
<div class="show" class:display={display}>
<button on:click={close}>
close
</button>
</div>
<style>
.capture {
background-color:cornflowerblue;
padding:1rem;
color:white
}
h1 {
background-color:lavender;
padding:1rem;
color:coral
}
.show {
position:absolute;
top:0;
width:100vw;
height:100vh;
background-color:rgba(0,0,0,0.5);
display:none;
}
.display {
display:block;
}
</style>
UPDATE
I recreate the code in codepen and it works, so it's a svelte problem? or just the svelte REPL environment problem? I need to implement in my own svelte environment later.

The REPL does some click/navigation interception. The given code should work in a real environment.

Related

Loading gif in a SharePoint 2013 page

The expected functionality is: on button click, a PPT gets downloaded(this comes from a REST call from an external site), in the meantime when the PPT is getting downloaded, a loading gif should be shown in the page and it should be stopped after the PPT is downloaded.
I've tried setTimeout() function, but it doesn't seem to be working right in this case.
Is it possible to implement through jQuery or javascript? Any help would be appreciated!
My test code:
<img src="/_layouts/15/images/loading16.GIF" style="display: none;" id="img">
<input type="button" value="download" id="download">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/sprestlib#1.8.0/dist/sprestlib.min.js"></script>
<script>
$("#download").click(function(){
$("#img").css("display","");
sprLib.file('Doc/Presentation.pptx').get()
.then(function (blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", _fileName);
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
setTimeout(function () { document.body.removeChild(link); }, 500);
}).then(function(){
$("#img").css("display","none");
});
})
</script>
Test result:

Chrome Extension add button to each image on a page

I am trying to append a button to each image on a webpage using a Chrome Extension. I have the following code in my content script:
var imagesArray = document.getElementsByTagName("img");
console.log(imagesArray);
for (const img of imagesArray) {
var button = document.createElement("button");
button.innerHTML = "button";
button.onclick = function() {
console.log("clicked");
}
img.append(button);
}
I am able to get all the images and I know I can append buttons, I just don't know how to append the button onto the image. Any help is appreciated
Use this line document.body.appendChild(button); <-- use this line down this img.append(button)
You can use something like this in the css. If you are able to add any css. Thanks
button {
display: none;
}
img:hover + button {
display:block;
}
<img src="https://picsum.photos/id/237/200/300" />
<button>My Button</button>

Mouse over the <a> tag

There is a prompt in the lower left corner When I put the mouse over the tag,
and can u tell me how to forbid this phenomenon.enter image description here
As commented, the behaviour that you wish to stop is a browser's feature.
To avoid this, you will have to simulate anchor's behaviour on your own but as you said you have many anchors and you cannot manually convert them to buttons, you can try following code:
function maskAnchors() {
var els = document.querySelectorAll('a[href]');
console.log("Anchors Found: ", els.length)
for (var i = 0; i < els.length; i++) {
els[i].setAttribute("data-url", els[i].getAttribute('href'));
els[i].removeAttribute("href");
els[i].addEventListener("click", handleClick)
}
}
function handleClick() {
var url = this.getAttribute('data-url');
window.open(url)
}
document.getElementById('btnAdd').addEventListener("click", function() {
var container = document.querySelector('.content');
var link = document.createElement('a')
link.href = "www.google.com";
link.textContent = "This is a newly added link";
container.append(link)
})
document.getElementById('btnMask').addEventListener("click", maskAnchors)
window.addEventListener('load', maskAnchors)
.maskedAnchor {
color: -webkit-link;
text-decoration: underline;
cursor: auto;
}
<div class="content">
Google
Facebook
StackOverflow
YouTube
Example
<a>blabla</a>
</div>
<button id="btnAdd">Add Anchor</button>
<button id="btnMask">Run masking</button>
Note:
Removing href will change styling. You will also have to do that manually.
This will not handle any anchors added dynamically after execution of this function. You will have to call this function again. I have optimised function to only fetch anchors that has href
Hope it helps!

export html table as word file and change file orientation

I have jquery function which exporting html table to word file. Function works great, but I need to rotate a word file to landsacpe orientation. Can somebody help me?
Here is js function:
<SCRIPT type="text/javascript">
$(document).ready(function () {
$("#btnExport").click(function () {
var htmltable= document.getElementById('tblExport');
var html = htmltable.outerHTML;
window.open('data:application/msword,' + '\uFEFF' + encodeURIComponent(html));
});
});
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.docx");
Export HTML to Microsoft Word
You may set page orientation, paper size, and many other properties by including the CSS in the exported HTML. For a list of available styles see MS Office prefixed style properties Some styles have dependencies. For example, to set mso-page-orientation you must also set the size of the page as shown in the code below.
Updated:
Tested with Word 2010-2013 in FireFox, Chrome, Opera, IE10-11. Minor code changes to make work with Chrome and IE10. Will not work with legacy browsers (IE<10) that lack window.Blob object. Also see this SO post if you receive a "createObjectURL is not a function" error: https://stackoverflow.com/a/10195751/943435
Update 2022:
Fixed broken GitHub link
#page WordSection1{
mso-page-orientation: landscape;
size: 841.95pt 595.35pt; /* EU A4 */
/* size:11.0in 8.5in; */ /* US Letter */
}
div.WordSection1 {
page: WordSection1;
}
To view a complete working demo see: https://jsfiddle.net/78xa14vz/3/
The Javascript used to export to Word:
function export2Word( element ) {
var html, link, blob, url, css;
css = (
'<style>' +
'#page WordSection1{size: 841.95pt 595.35pt;mso-page-orientation: landscape;}' +
'div.WordSection1 {page: WordSection1;}' +
'</style>'
);
html = element.innerHTML;
blob = new Blob(['\ufeff', css + html], {
type: 'application/msword'
});
url = URL.createObjectURL(blob);
link = document.createElement('A');
link.href = url;
link.download = 'Document'; // default name without extension
document.body.appendChild(link);
if (navigator.msSaveOrOpenBlob ) navigator.msSaveOrOpenBlob( blob, 'Document.doc'); // IE10-11
else link.click(); // other browsers
document.body.removeChild(link);
};
And the HTML:
<button onclick="export2Word(window.docx)">Export</button>
<div id="docx">
<div class="WordSection1">
<!-- The html you want to export goes here -->
</div>
</div>

How to style hyperlink after scheme is removed with Javascript?

So I am trying to display a url that is caught by Javascript. It is returned to JS in the form http://i.mygreatsite.com, but I would like to cut the schema off to make it cleaner, and have the actual code look something like
<a href=http://i.mygreatsite.com>i.mygreatsite.com</a>
Before I tried doing this, I had to set some special attributes on the url, namely setting target to blank so it would open in a new tab and changing the color of the hyperlink to black, as the rest of the links on the page are blue. I went about it like this:
init: function() {
this.on("success", function(file, responseText) {
var span = document.createElement('span');
var a = document.createElement('a');
a.href = responseText;
a.innerHTML = responseText;
a.setAttribute('target', '_blank');
a.style.color="black";
span.appendChild(a);
span.setAttribute("style", "position: absolute; box-sizing: border-box; -webkit-box-sizing: border-box; bottom: -28px; left: 3px; right: 3px; height: 28px; word-wrap: break-word; line-height: 28px; text-overflow: ellipsis; ");
file.previewTemplate.appendChild(span);
});
}
Everything worked fine with it, but when I went to remove the schema I did it by using regex:
repl = responseText.replace(/(https?:\/\/(\S+))/i, "<a href='$1'>$2</a>");
a.href = repl;
a.innerHTML = repl;
a.setAttribute('target', '_blank');
a.style.color="black";
Now the schema is removed, but none of the attributes I set previously that were working before are there now. The URL is blue and opens in the same tab. Am I missing something here? Thanks.
What you've ended up with is an anchor within another anchor:
<a target="_blank" style="XXX">myurl</a>
That's because of setting the innerHTML of the anchor you're trying to create. Setting styles on an element will not cascade (you should really use CSS Stylesheets instead) and of course the target element will not apply as it's technically not the hyperlink you're clicking on!
Instead, just set the innerHTML using the $2 result of your Regex.
Edit
So your updated code would need to be similar to:
repl = responseText.replace(/(https?:\/\/(\S+))/i, "$2");
a.href = responseText;
a.innerHTML = repl;
a.setAttribute('target', '_blank');
a.style.color="black";
//Or if you wanted to use CSS stylesheets
a.className = "myCssClass"

Categories

Resources