高阶函数导致 chrome 扩展中的不安全评估

high-order function causes unsafe eval in chrome extension

我正在做一个非常简单的 chrome 扩展来随机更改我 chrome 书中的墙纸。但是我在加载 Javascript 控制台后收到一个奇怪的错误:

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". @ background.js:27

这是我的 manifest.json:

{
  "manifest_version": 2,

  "name": "Abyss Wallpapers for Chrome OS",
  "description": "Sets the Chrome OS wallpaper to a random wallpaper from the
                      Wallpaper Abyss (wall.alphacoders.com), once a minute",
  "version": "1.0",
  "background":
  {
    "scripts":["background.js"]
  },
  "permissions": [
    "wallpaper",
    "https://wall.alphacoders.com/api2.0/",
    "background"
  ]
}

这是我的 background.js:

var baseUrl = "https://wall.alphacoders.com/api2.0/get.php?"
var apiKey = "c160c64ef4c79e61e325ddf944183dfe"
var params = "auth=" + apiKey + "&method=random"
var interval = 30000;
var xhr = new XMLHttpRequest();
xhr.open("GET", baseUrl + params, true);
xhr.onreadystatechange = function()
{
  if (xhr.readyState == 4 && xhr.status == 200)
  {
    var data = xhr.responseText;
    if (data.success)
    {
      chrome.wallpaper.setWallpaper
      (
        {url:data.wallpapers[1].url_image,
        layout:"CENTER_CROPPED",
        filename:data.wallpapers[1].id + "." + data.wallpapers[1].file_type},
        function(thumbnail)
        {
          thumbnail = null;
        }
      )
    }
  }
}
setInterval(xhr.send(), interval);

它似乎拒绝了 setInterval() 方法,但是那里没有 eval 甚至没有字符串。

编辑:所以我更改了 setInterval() 语句以反映 Bergi 的回答,现在后台脚本运行了大约一分钟,这意味着设置了间隔,但之后我又收到另一个错误:

Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.(anonymous function) @ background.js:27

为什么我在第 5 行专门调用 xhr.open() 时对象没有打开?

setInterval,当被传递一个非函数值时,第一个参数是一个代码字符串并且evals它。您正在传递 xhr.send() 的 return 值,这确实不是函数。

使用

解决这个问题
setInterval(function() { xhr.send(); }, interval);

setInterval(xhr.send.bind(xhr), interval);

我猜这也是你真正打算做的。

创建 XHR 后 .send() 只能 .send() 一次。

如果您需要间隔执行此操作,则需要每次都重新创建 XHR。