2010-12-15 75 views
1

我一直在为Facebook使用Chrome编写一个Greasemonkey脚本(拖放作为扩展)。我知道Greasemonkey是沙盒,至少就Firefox而言,除非在浏览器中更改设置,否则无法关闭含脚本的窗口。但是,我知道大多数浏览器都允许父窗口关闭子窗口,而不需要用户的确认。无论如何,我试图让我的脚本打开一个窗口,从HTML对象中获取文本片段,然后在页面上按下按钮关闭窗口。用Greasemonkey关闭窗口

我打开窗口代码如下所示:

function birthday(linkAddress) { 
var winNew=window.open(linkAddress, "_blank", "height=100", "width=100"); 
/*code to be run on page*/ 
    winNew.close() 
} 

的窗口打开罚款,但我得到了Chrome浏览器中的JavaScript错误说“不能调用方法‘关闭’的未定义”。我认为我的对象与Greasemonkey沙盒相关有些问题,但我无法确定是什么。是否可以在Chrome中使用Greasemonkey脚本关闭窗口?我需要启用一些设置吗?或者我的代码错了?请记住,这段代码是通过我设置的主窗口页面中的一个函数运行的,它使用我写入页面的按钮的onClick事件在脚本中设置为一个函数。还有任何提示访问子页面上的DOM元素将不胜感激。

感谢您的帮助!

(对不起,我很新,以及不与编程实践中,这是第一次我写了一个脚本Greasemonkey的)

回答

0

的代码发布的片段不足和不匹配规定“按下页面上的按钮关闭窗口”的操作。

所以最好的猜测是关闭功能在birthday()之外(其中winNew已定义)或者未显示的代码中的某些内容导致了问题。

另一个需要注意的是Greasemonkey脚本也可能触发子窗口 - 取决于打开子窗口时是否指定了哪个URL。

下面是按下按钮打开和关闭子窗口的示例代码:
See it in action at jsfiddle

<html> 
<head> 
<script type="text/javascript"> 
    var chldWnd; 

    function OpenChldWin() 
    { 
     //chldWnd = window.open ("http://www.google.com"); 
     chldWnd = window.open ('','','height=200, width=200'); 
     chldWnd.document.write ('<p>My New Window</p>'); //-- Don't do if opening a URL in new window. 
     chldWnd.focus(); 
    } 

    function CloseChldWin() 
    { 
     if (chldWnd.closed) 
      alert ('Child window was already closed.'); 
     else 
     { 
      chldWnd.close(); 
      alert ('Child window is NOW closed.'); 
     } 
    } 
</script> 
</head> 
<body> 
<input type="button" value="Open Child Window"  onclick="OpenChldWin()"> 
<input type="button" value="Close the Child Window" onclick="CloseChldWin()"> 
</body> 
</html> 
+0

我想我的问题的一部分也是,我认为我是从页面运行的代码,但实际上我并不是。感谢您的帮助澄清。我将再次尝试,并在必要时添加位置黑客。 – Matt 2010-12-16 19:57:08