2013-07-25 64 views
1

我正在制作一个GreaseMonkey脚本,它在页面上粘贴一个按钮。当点击这个按钮时,它会拉起一个新的页面。理想情况下,我希望能够像常规HTML页面一样格式化此页面。我拥有的约束是我无法创建一个新的HTML文件。所有生成的内容都需要来自GreaseMonkey脚本。格式化document.write()的内容

function openWin() 
     { 
     myWindow=window.open('','','width=400,height=500'); 
     myWindow.document.write("Hello World"); 
     myWindow.focus(); 
     } 

我想放的不仅仅是世界您好更多在于此:点击时

我的GreaseMonkey坚持在原来的页面

<input type="button" value="push me" onclick="openWin()"> 

调用该函数的身体这个代码打开新窗口。我想在那里放一张桌子,放置文字,放入图片等。有没有一种非杂乱的方式来做到这一点?

在此先感谢。

回答

1

聪明和容易的事情是使用GM_getResourceText()Doc

这样的话,你只要把你的弹出页面最简单的方式,在页面加载本地,就像你的GM脚本,您填充你有3个简单的代码行智能弹出。

例如,创建两个文件如下:

Popup_fun.user.js

// ==UserScript== 
// @name  _Fancy popups, the smart way 
// @include http://YOUR_SERVER.COM/YOUR_PATH/* 
// @include http://stackoverflow.com/questions/* 
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js 
// @resource popupSrcRz PopupPage.htm 
// @grant GM_getResourceText 
// ==/UserScript== 

//-- Don't refire on the popup. 
if ($("#gmDontFireOnMe").length === 0) { 

    $("body").prepend (
     '<button id="gmLaunchPopup">Launch a fancy popup</button>' 
    ); 
    $("#gmLaunchPopup").click (openWin); 
} 

function openWin() { 
    var popupSrc = GM_getResourceText ("popupSrcRz"); 

    myWindow=window.open ('','','width=400,height=500'); 
    myWindow.document.write (popupSrc); 
    myWindow.document.close(); 
    myWindow.focus(); 
} 


PopupPage.htm

<!DOCTYPE html> 
<html><head> 
    <title>My fancy popup</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <style type="text/css"> 
     body { padding: 0 3ex; } 
     table { 
      margin: 1em; 
      padding: 0; 
      border-collapse: collapse; 
      border: 1px solid darkBlue; 
     } 
     th, td { 
      margin: 0; 
      padding: 0.8ex 1em; 
      vertical-align: top; 
      text-align: left; 
      border: 1px solid darkBlue; 
     } 
     th { background: lightYellow; } 
     img { max-width: calc(100% - 3ex); } 
    </style> 
</head><body> 

<p id="gmDontFireOnMe">I'm the popup page.</p> 

<p>Here's a table:</p> 
<table class=""> 
    <tr><th>Thing</th><th>Qty</th></tr> 

    <tr><td>Flux</td><td>88</td></tr> 
    <tr><td>Capacitor</td><td>88</td></tr> 
</table> 

<p>Here's an image:</p> 
<img src="http://media2.s-nbcnews.com/j/MSNBC/Components/Photo/_new/tdy-121010-puppies-03.grid-6x2.jpg" 
    alt="Awwww!"> 
</a> 

</body></html> 


保存这两个文件在同一目录下(而不是在系统临时文件夹),并安装Popup_fun.user.js,使用Firefox的开放菜单(按CtrlØ)。 当您重新加载此页面并单击该按钮时,您将看到一个不错的格式化弹出窗口。

如果您将脚本托管在某处,只需将PopupPage.htm复制到同一文件夹。它会在你的脚本安装时自动安装。

+0

这是如此弧度。非常感谢! –

+0

不客气,乐意效劳! –

1

您可以创建这个使用已经存在的线:

myWindow.document.write("<table><tr><td style='color:blue'>Do your styling</td></tr></table>"); 

浇你的HTML,其中的“Hello world目前”

OR

您使用创建DOM元素:

var d=document.createElement('div'); 
d.style.color="blue"; 

然后附加到窗口对象。

myWindow.appendChild(d);