开发者

javascript page source help

Currently I am writing a system for a user that on filling in a form it creates a template for a HTML email that will be able to use with their CRM system, the issue is that you user is a bit docile and for the live of them cannot understand how to view the source of the page so they can copy and paste the template code into their CRM, what I am wanting is there to be able to have a link/button that user can click that will s开发者_JAVA百科how the source code in a window, I am in now way a javascript developer so any tips, hints examples would be great.


Well you probably want to do something like this: grab the "innerHTML" of the element containing your template HTML (or whatever it is). Then open a new window and drop the HTML into it, surrounded by a <pre> block. You'll also want to replace all the important markup characters with appropriate HTML entities, and probably replace newlines with <br> elements.

It'd probably be close to this (but it's not tested):

var html = document.getElementById('whatever').innerHTML
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/\r?\n/g, '<br>');

var w = window.open('', 'SourceWindow', 'height=500,width=600');
var d = w.document.open();
d.write('<html><body><pre>' + html + '</pre></body></html>');
d.close();

edit — if you want to strip script blocks, you could add this "replace" call to the series above:

.replace(/<\s*script[^>]*>.*?<\/\s*script[^>]*>/g, '')

That's a little shaky because in general trying to recognize HTML with a regular expression is not really possible. However, since script tags don't really contain markup and definitely end with the next closing script tag, it's less odious than the general case.


I think the best practice here isn't really to use a Javascript trick, but to copy the HTML template into a visible section and replace "<" with "&lt;", ">" with "&gt;" (escaping other bits as needed).

I would argue that it makes for poor usability to force a user to view the page source themselves, and it's not hard to use regex to make these replacements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜