No saving or outputting is possible in Javascript?

2019-09-14 19:50发布

问题:

In this question I just learned how to illicit one desired element out of a Google translate page. There I have also learned that placing anything into clipboard in Javascript is literately impossible (you can do it by prompting a window asking a user to save some value into the clipboard - but you can't do that automatically), which is a rather sad thing to me as I really need to save that element out of a Google translate page automatically.

I wonder if it's at least possible in Javascript to save some values in a separate file on my computer? In the w3schools.com tutorial on Javascript it is stated that "JavaScript does not have any print or output functions". Does that mean that saving info on my computer is absolutely impossible in Javascript?

回答1:

You can use this code:

// Assuming the text you want to save is in variable 'contentVar'
uriContent = "data:application/octet-stream," + encodeURIComponent(contentVar);
window.location.href = uriContent;

Your browser should then download a file that contains whatever is inside contentVar.

The downside of this is that you can't set the file name. Doing this in a cross-browser way is difficult, but as always, there's a library to help! FileSaver.js