最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why copy function is not working inside setTimeout? - Stack Overflow

programmeradmin0浏览0评论

Chrome complains when I try to copy inside setTimeout.

setTimeout(function () { copy('a') }, 0)

Uncaught ReferenceError: copy is not defined
    at <anonymous>:1:26

It doesn't work with the window scope as well.

setTimeout(function () { window.copy('a') }, 0)

Uncaught TypeError: window.copy is not a function

Interestingly, if I keep the reference to copy and reuse it, it works

cc = copy;
setTimeout(function () { cc('a') }, 0);

In Firefox, it doesn't throw any error, but it doesn't work even with the saved reference.

Why copy function doesn't work inside setTimeout, is it a bug?

Chrome complains when I try to copy inside setTimeout.

setTimeout(function () { copy('a') }, 0)

Uncaught ReferenceError: copy is not defined
    at <anonymous>:1:26

It doesn't work with the window scope as well.

setTimeout(function () { window.copy('a') }, 0)

Uncaught TypeError: window.copy is not a function

Interestingly, if I keep the reference to copy and reuse it, it works

cc = copy;
setTimeout(function () { cc('a') }, 0);

In Firefox, it doesn't throw any error, but it doesn't work even with the saved reference.

Why copy function doesn't work inside setTimeout, is it a bug?

Share Improve this question edited Feb 28, 2018 at 13:30 Sanghyun Lee asked Feb 28, 2018 at 11:42 Sanghyun LeeSanghyun Lee 23k19 gold badges105 silver badges126 bronze badges 2
  • stackoverflow.com/questions/18432072/… stackoverflow.com/questions/48934462/… – Josh Lee Commented Feb 28, 2018 at 12:11
  • Fun game: Add a Watch for window.copy. It's undefined. Now type debugger into the console and Watch it show up! – Josh Lee Commented Feb 28, 2018 at 12:43
Add a comment  | 

2 Answers 2

Reset to default 11

copy is part of the developer tools' Dev Tools Utilities API and is not available outside the browser console. For example, trying to execute the command in a JavaScript file that's part of a normal web page you'd get the same error.

When you invoke the command inside the setTimeout callback, the execution context is no longer the console so copy doesn't exist anymore.

Inspired by the mention of with in this answer, I discovered that you can use it to make copy() available in setTimeout() and other callbacks, instead of having to create a global reference to it:

with ({ copy }) { setTimeout(() => copy("copied!"), 0) }

copied! will now be on your clipboard. Unfortunately, this trick doesn't seem to work in Firefox's console.

发布评论

评论列表(0)

  1. 暂无评论