问题
What I'm trying to do is have a function create a uri anchor to redraw/rerender/(call it what you want) the entire page
Basically I want to be able to convert any page into a URI scheme so that when I navigate to such a link I get the entire page as is, kinda like saving a webpage. For example if I were to be editing a page and wanted to resume later with all the textareas just the way they are and the forms filled out, or if I wanted to save someones (small) page without having to worry that his site will go down and without having to save files on my computer (I want to use bookmarklets)
Here's what I have so far:
html = '<html>' + document.documentElement.innerHTML + '</html>';
//html = html.replace(/"/g, '\\"');
a = document.createElement('a');
a.href = 'data:text/html;charset=utf-8,' + html;
a.innerHTML = 'click here';
document.body.appendChild(a);
You see what I'm trying to do. Ok now the hard part is somehow using a regex to replace all double quotes that are already in double quotes but not ones that aren't.
For example if we create the page
<html><body>Testing</body></html>
and run the function enough times we're gonna get some issues with the 3rd and on links.
See what I mean: http://jsfiddle.net/AvSh3/3/
回答1:
Use the built-in escape() function:
html = escape(html);
回答2:
I've reworked it into
var html = '<html>' + $("html").html() + '</html>';
$('<a></a>').html("click here")
.attr("href", 'data:text/html;charset=utf-8,' + escape(html))
.appendTo($("body"));
Which doesn't display correctly, but when viewing source everything looks correct. Maybe some other special parameter is required?
回答3:
This works when testing on my own page:
a = document.createElement('a');
a.href = 'data:text/html;charset=utf-8,<html>' +
escape(document.documentElement.innerHTML) + '</html>';
a.innerHTML = 'click here';
document.body.appendChild(a);
I'm guessing that it's just a jsBin/jsFiddle technicality but I have no clue why. Anyway if people want to use this to make bookmarklets heres the link:
....
Well I can't figure out how to make a bookmarklet link in SO, if you want just create a new bookmark with this location:
javascript:a=document.createElement("a");a.href="data:text/html;charset=utf-8,<html>"+escape(document.documentElement.innerHTML)+"</html>";a.innerHTML="click here";document.body.appendChild(a);
Anyway with this fun tool we can do things like Jon does in the first link here:
http://wundes.com/bookmarklets.html
来源:https://stackoverflow.com/questions/4481348/save-current-page-state-using-javascript