简体   繁体   中英

How do I close a firefox tab from a greasemonkey script?

I have a greasemonkey user script with this single line of code...

window.close();

but firefox does not allow a user script to close a window (as reported by an error message in the error console)

Is there a work around to this problem?

You need to change configuration settings of Firefox (about:config) to allow this.

Steps:

  1. Go to address bar and type about:config
  2. Go to parameter dom.allow_scripts_to_close_windows
  3. Set its value as true

Now your script can close the TAB with 'window.close()'

eg.

function closeTab(){
    window.open('', '_self', '');
    window.close();
} 

由于 Firefox 以与外部网站上的脚本代码相同的权限对待 Greasemonkey 代码,因此不可能只允许 Greasemonkey 代码能够关闭窗口,而不允许常规脚本。

By now some of the -monkies allow the use of @grant option to officially unlock commands like window.close() without going to about:config . For example, in Tampermonkey :

// @grant window.close
// @grant window.focus

(The latter grant allows you to re-focus the browser on your window.) This would remove the error.

EDIT: As @baptx correctly mentions in the comments, the browser's security options should be set to allow scripts to close windows, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM