我当前正在运行一个节点js文件,并且收到这样的帖子。

app.post('/', function (req, res) {
    var firstLine = req.body.firstLine;
    var secondLine = req.body.secondLine;
    var previewID = req.body.previewId;
    takeWebshot(firstLine)
    return res.end('<h1>Hello, Secure City World!</h1>');
});


当我console.log firstLine设置为req.body.firstLine时,我们说它是“ Hello”。因此firstLine =“ Hello”。
然后,我将此变量传递给takeWebshot(firstLine)
当我在takeWebshot中管理日志fLine时,我可以看到“ Hello”。

    function takeWebshot(fLine) {
console.log(fLine);
        var options = {
          onLoadFinished: {
            fn: function() {
              document.getElementById("user_input").value=fLine;
              document.getElementById("second_user_input").value="AMAZON USERNAME";
              document.getElementById("preview_btn").click();
            }
          },
          takeShotOnCallback: true,
          captureSelector: '.fancybox-outer'
        };

        webshot('example.com/testy.html', './example.png', options, function(err) {
          if (err) return console.log(err);
          console.log('OK');
        });
      };


这是我这一行的问题:

document.getElementById("user_input").value=fLine;


fLine不再读取。我尝试将fLine传递给函数,就像fn:function(fLine)一样。 fLine现在等于“成功”。以我对JS的有限了解,似乎函数fn:function()是主节点模块网络快照中的promise回调。我需要的目标

document.getElementById("user_input").value=fLine; to equal firstLine that is being sent by the other function.


编辑:webshot正在调用幻影js打开无头的url。我正在尝试传递变量,以便它可以在调用屏幕截图时填写表格。这就是为什么它有文件。

最佳答案

webshot的文档提到脚本将在传递给Phantom之前先进行序列化


  请注意,脚本将被序列化,然后作为文本传递给Phantom,因此所有变量作用域信息都将丢失。但是,可以将调用者的变量传递给脚本,如下所示:


cf https://www.npmjs.com/package/webshot#phantom-callbacks

因此,您应该遵循他们的指示,并进行如下操作:

onLoadFinished: {
  fn: function() {
    document.getElementById("user_input").value=this.fLineSnapshot;
    document.getElementById("second_user_input").value="AMAZON USERNAME";
    document.getElementById("preview_btn").click();
  },
  context: {
    fLineSnapshot: fLine
  }
},

关于javascript - 无法在从另一个函数调用它的函数中设置变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53345475/

10-10 00:19
查看更多