以编程方式打开“查看源代码”使用 Javascript 在浏览器中显示 HTML 窗口?

发布于 2024-08-13 05:54:03 字数 72 浏览 9 评论 0原文

如何以编程方式打开“查看源代码”窗口(使用一些 JavaScript),就像在浏览器中右键单击并单击“查看源代码”一样?这可能吗?

How do I programmatically open the "View Source" window (using some Javascript) like when I right click in the browser and click "View Source"? Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

_蜘蛛 2024-08-20 05:54:03

您可以使用 Firefox、Chrome 和旧版 IE 支持的“查看源”URI 架构。

不需要 JavaScript,只需一个指向您希望用户在源代码视图中看到的页面的普通链接:

<a target="_blank" href="view-source:http://www.wikipedia.org/">view Wikipedia's home page HTML source</a>

更多信息:

http://en.wikipedia.org/wiki/View-source

You can use the "view-source" URI schema, supported by Firefox, Chrome, and older versions of IE.

No JavaScript required, just a normal link to the page you want the user to see in source view:

<a target="_blank" href="view-source:http://www.wikipedia.org/">view Wikipedia's home page HTML source</a>

More info:

http://en.wikipedia.org/wiki/View-source

猫七 2024-08-20 05:54:03

您可以使用此脚本,我们只需获取 html 标记的innerHTML,重新附加它,然后将其粘贴到弹出窗口中。

function showSource(){;
    var source = "<html>";
    source += document.getElementsByTagName('html')[0].innerHTML;
    source += "</html>";
    //now we need to escape the html special chars, javascript has escape
    //but this does not do what we want
    source = source.replace(/</g, "<").replace(/>/g, ">");
    //now we add <pre> tags to preserve whitespace
    source = "<pre>"+source+"</pre>";
    //now open the window and set the source as the content
    sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
    sourceWindow.document.write(source);
    sourceWindow.document.close(); //close the document for writing, not the window
    //give source window focus
    if(window.focus) sourceWindow.focus();
}  

这不会完全显示源代码,因为它不会显示 HTML 标记之外的任何内容,也不会显示 html 标记内的任何属性,但它应该足够接近,并且可以跨浏览器工作。

该解决方案相对于 view-source: 解决方案的优点是它也可以在 internet-explorer 6> 中工作。在 Windows XP SP2 上,差不多就是这样。如果您的受众都不属于该组,请使用查看源选项,这样更简单。

You could use this script, we simply grab the innerHTML of the html tag, reappend that, and paste that in a popup.

function showSource(){;
    var source = "<html>";
    source += document.getElementsByTagName('html')[0].innerHTML;
    source += "</html>";
    //now we need to escape the html special chars, javascript has escape
    //but this does not do what we want
    source = source.replace(/</g, "<").replace(/>/g, ">");
    //now we add <pre> tags to preserve whitespace
    source = "<pre>"+source+"</pre>";
    //now open the window and set the source as the content
    sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1');
    sourceWindow.document.write(source);
    sourceWindow.document.close(); //close the document for writing, not the window
    //give source window focus
    if(window.focus) sourceWindow.focus();
}  

This will not completely show the source as it will not show anything outside the HTML tags, or any properties inside the html tag, but it should be close enough, and works cross-browser.

The advantage of this solution over the view-source: solution is that it will also work in internet-explorer 6> on windows XP SP2, that's pretty much it. If none of your audience is in this group, go with the view-source option, its way simpler.

物价感观 2024-08-20 05:54:03

这将为支持 view-source: 模式的浏览器

javascript:void(window.open('view-source:'+location.href))

执行此操作。可以从此 scURIple 中的链接制作一个书签来执行此操作:

data:text/html;charset=utf-8,<html>
       <a href="javascript:void(window.open('view-source:'+location.href))">view-source</a>
</html>

这样的书签可以在具有任意 URI 的任何页面上使用schema 而不仅仅是 http: 或基于 HTML 的页面(因此缺乏 .innerHTML 等属性)。

因此,URI(这些 scURIples 适合立即模式渲染):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

可以直接检查:

view-source:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

-------------------------------------------------------- -------------------------

注意:制作上述小书签是一种矛盾且多余的做法,因为一般来说,支持view-source: 模式(协议)直接在用户界面中实现它 - 然而有些界面严重受损,这就是为什么在使用以下书签时特别需要:

window.navigator.userAgent=
         Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
                                                                                    (Splashtop-v1.2.17.0)

Splashtop“即时启动”(非)环境由Device VM严重截肢FF。

(提示:

   <a href="javascript:void(window.open('view-source:file:///'))">
         use view-source to traverse and peruse Splashtop system files</a>

浏览Splashtop目录结构的书签,一般即:view-source:file://media/

------------------ -------------------------------------------------- -

魔鬼让我这么做 - 忍不住要解释:

...此链接(原文如此 view-source:)可以在具有任意架构 URI 的任何页面上使用...

包括它本身,观察 URI:

view-source:view-source:view-source:view-source:view-source:about:blank

产生一个明显的 HTML 源,因此 < strong>有 .innerHTML 属性

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                                                                 <html><head><title></title></head><body></body></html>

,但

view-source:view-source:view-source:view-source:view-source:about:logo

不是 HTML 源,因此没有 .innerHTML 属性。

至于

任意模式的 URI:

 view-source:jar:,   view-source:chrome:,   view-source:place:,  ... ?

大概,这基本上是这样 - 只要浏览器可以使用具有特定模式的 URI 呈现页面,那么该页面必须具有可以显示的可解释源,因此可见,无需解释渲染。

(即,view-source:place:... 不会生成任何可行的页面,但 place:... URI 也不会生成任何可行的页面,尽管这样的 URI 可以添加书签- 至少对于 FF [ v.>3.04 ] )

所以......

<a href='view-source:javascript:with(document){write(42);close();}' >v-s:js: answer</a>  
<a href=                    'javascript:with(document){write(42);close();}' >js: question</a>

This will do it for broswers supporting the view-source: schema

javascript:void(window.open('view-source:'+location.href))

A bookmarklet to do this can be made from the link in this scURIple:

data:text/html;charset=utf-8,<html>
       <a href="javascript:void(window.open('view-source:'+location.href))">view-source</a>
</html>

Such a bookmarklet can be used on any page with a URI of an arbitrary schema and not just http: or pages that are HTML based (and hence devoid of properties like .innerHTML).

Thus the URI for (these scURIples are amenable to immediate mode rendering):

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

can be examined directly with:

view-source:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABnElEQVQ4jWNgwAMaGBiYHqdqT36SpvP/carOgdueKuz41OM2JE177ZM0nf+PUrUXkmwAAwMDw91QJf7HKTqnn6Tp/H+UplNNUMOrqaw5r6ew1D2fxCAKE3uYpKv0OEX3KdQlETg1P+5j4Hw9he3q66ls/19NZX35agpLzcsJDOIMDAwMj5O1zR6n6P54nKb942GqpgtWAxoaGJheTWVQeTeNqe31VJbPUINev5rB0ny/gUHgSbaqz5Mk/T+Pk3UbCXrlQT+D5NupTE3vpjG9fTOV9f+racxvXvZzND0tk/JrYGBgwtCwqtCSc3WFQ/GqEqfAZYWO2vMTFDgYGBgYrjaI8jybyFn0bhrTo3fTmf6/mc4gjdXGVcW2WmsrHP/D8OpypzcrS10OrC53bN1QaRVypFkj6FaPSCROJ88sd+FfV2YdtKHCrmV9he3ODeW29zZU2P1fX2H/f2254//VZU7/VxY72WFozM3J+Z+bk/Mfq6HFviJzy31tFld4payscJ44s8BdEkM9sgCMjQtjtZCqBhADcBpAKqaKAQB1iiloT36niAAAAABJRU5ErkJggg==

---------------------------------------------------------------------

Note: Making the above bookmarklet is an oxymoron and redundant since generally, browsers that support the view-source: schema (protocol) implement it directly in the user interface - however some interfaces are severely crippled which is why this bookmark is especially necessary when using:

window.navigator.userAgent=
         Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
                                                                                    (Splashtop-v1.2.17.0)

The Splashtop "Instant On" (not) environment by Device VM seriously amputates FF.

(hint: bookmark

   <a href="javascript:void(window.open('view-source:file:///'))">
         use view-source to traverse and peruse Splashtop system files</a>

to browse the Splashtop directory structure, generally ie: view-source:file://media/)

---------------------------------------------------------------------

the devil made me do it - can't resist expounding upon:

... this link (sic view-source:) can be used on any page with a URI of an arbitrary schema ...

including itself, observe the URI:

view-source:view-source:view-source:view-source:view-source:about:blank

produces an obvious HTML source and so has an .innerHTML property

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                                                                 <html><head><title></title></head><body></body></html>

but

view-source:view-source:view-source:view-source:view-source:about:logo

is not an HTML source and so does not have an .innerHTML property.

As for

a URI of an arbitrary schema:

 view-source:jar:,   view-source:chrome:,   view-source:place:,  ... ?

Presumably, this is elementarily so - as long as the browser can render a page with a URI with a particular schema then that page must have an interpretable source that can be shown, ergo viewable, w/o an interpreted rendering.

(ie. view-source:place:... does not produce any viable page but then neither does a place:... URI though such a URI can be bookmarked - at least with FF [ v.>3.04? ] )

so ...

<a href='view-source:javascript:with(document){write(42);close();}' >v-s:js: answer</a>  
<a href=                    'javascript:with(document){write(42);close();}' >js: question</a>
如何视而不见 2024-08-20 05:54:03

根据您的使用情况,一种解决方案是将其作为 Firefox 插件或类似组件。

One solution, depending on your usage, is to do it as a Firefox add-on or similar.

一刻暧昧 2024-08-20 05:54:03

有2个选项   [和一个解决方法,我稍后会解释..]

#1。 “HTML” 来自 DOM,

//get HTML from DOM (not really HTML from the server but an interrupted one - the plus is that it is immediate to fetch).
(function(){
  "use strict";

  var d = document.createElement("div");
  d.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";
  d.appendChild(document.createTextNode(document.querySelector('html').innerHTML));
  document.querySelector('body').appendChild(d);
}());

这是“安全”结果,没有 包装和 doctype
来自 DOM

#2。来自服务器的 HTML(通过“Self-Ajax”)

//get HTML from server, its the real-deal, but requires internet-connection (again...), since its the same-page you are OK to Ajax (domain wise..)
(function(){
  var xhr = new XMLHttpRequest();
  xhr.responseType = "text";
  xhr.onreadystatechange = function(e){
    var 
      xhr = e.target
      , d = document.createElement("div")
      ;

    if(xhr.DONE !== xhr.readyState) return;

    d.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";

    d.appendChild(document.createTextNode(xhr.responseText));
    document.querySelector('body').appendChild(d);
  }
  xhr.open("GET", String(window.location.href), true);
  xhr.send();
}());

我已经在控制台中运行了这两个页面,在当前页面 (当然在我写这个答案之前..)

这是并排的结果,注意差异。

Side By Side

注释和内容...:

There are 2 options   [ and a workaround, which I will Explain later.. ]

#1. "HTML" From D.O.M

//get HTML from DOM (not really HTML from the server but an interrupted one - the plus is that it is immediate to fetch).
(function(){
  "use strict";

  var d = document.createElement("div");
  d.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";
  d.appendChild(document.createTextNode(document.querySelector('html').innerHTML));
  document.querySelector('body').appendChild(d);
}());

this is the 'safe' result, without the <html> wrapping and doctype:
from DOM

#2. HTML From Server (Through "Self-Ajax")

//get HTML from server, its the real-deal, but requires internet-connection (again...), since its the same-page you are OK to Ajax (domain wise..)
(function(){
  var xhr = new XMLHttpRequest();
  xhr.responseType = "text";
  xhr.onreadystatechange = function(e){
    var 
      xhr = e.target
      , d = document.createElement("div")
      ;

    if(xhr.DONE !== xhr.readyState) return;

    d.style.cssText = "max-width:500px; max-height:200px; background-color:rgba(223,223,223,.7); border:3px solid rgba(0,0,0,.5); padding:5px; margin:10px; overflow-x:hidden; overflow-y:auto; word-break:break-word; font-family:'Courier New',Consolas,Lucida Console,monospace,sans-serif; text-shadow:.3px .3px rgba(0,0,0,.2),-0.3px -0.3px rgba(0,0,0,.2); border-radius:5px; box-shadow:1px 1px 5px rgba(0,0,0,.3),-1px -1px 5px rgba(0,0,0,.3)";

    d.appendChild(document.createTextNode(xhr.responseText));
    document.querySelector('body').appendChild(d);
  }
  xhr.open("GET", String(window.location.href), true);
  xhr.send();
}());

I've ran both in the console, in this current page (naturally before I've wrote this answer..)

and this is the side by side result, notice the difference.

Side By Side

notes and stuff..:

  • you might use the html's outerHTML (but its not always available in every standard DOM)
  • ease up your server's load by compiling/rendering the page's source dynamically in client-side using mustache or handlebars.
  • you can store the text of the page, before any (most) of the modifications in the localStorage, fork the code above, and make a small (and wonderful) script, place this script in the page's head just before you start modifying the page's source..
无声无音无过去 2024-08-20 05:54:03

最简单的事情就是使用这 1 行 Javascript:

//function showSource() {

window.location = "view-source:" + window.location;

//}

我希望它与您的浏览器兼容!

The Simplest Thing To Do Is Use This 1 Line Of Javascript:

//function showSource() {

window.location = "view-source:" + window.location;

//}

I Hope Its Compatible With Your Browser!

你对谁都笑 2024-08-20 05:54:03

您可以执行以下操作,但它不会是原始 HTML 源:循环遍历 DOM 并通过输出您找到的节点的属性/值来重新创建源。

这不是一项容易的任务(实际上是一项艰巨的任务),但它是您唯一的选择。

谢谢

。我想这就是FF正在做的事情,因为来源之间总是存在着微妙的差异。

You could do the following but it won't be the original HTML source: Loop through the DOM and re-create the source by outputting the properties/values of the nodes you find.

It is not an easy task (a huge one in fact), but it is pretty your only option.

Thanks

PS. I think this is what FF is doing, because there is always a subtle difference in the sources.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文