从location.href =“ javascript:someFunction()”获得价值?

时间:2019-06-01 12:55:25

标签: javascript

是否可以通过用location.href='javascript:someFunction()触发该函数来获取该函数返回的值?

/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = location.href='javascript:someFunction()';

// Is it possible to get the returned value this way?

我知道还有其他解决方案和可能性,但我正在寻找一个简单的答案,是否可以接收像这样的返回值,如果可以,怎么办?

感谢您的答复。

2 个答案:

答案 0 :(得分:0)

您可以操纵字符串,以便将返回的值作为参数传递给新的回调函数:

function callback(response) {
    console.log("returned value was " + response);
}

location.href='javascript:callback(someFunction());';

请注意,href代码仅在当前调用堆栈为空时才执行。换句话说,它异步运行。因此,不可能像您的代码试图同步获得返回值一样。它不能为var returned = location.href(....)

如果函数的名称(someFunction)可以作为字符串使用,则可以使用一个承诺来处理该异步性:

function someFunction() {
    console.log("called");
    return "returned";
}

function execute(func) {
    return new Promise(function (resolve) {
        window.__callback = resolve;
        location.href='javascript:__callback(' + func + '())';
    });
}

execute("someFunction").then(function (response) {
    console.log("response = " + response);
});

答案 1 :(得分:0)

如果我很好地理解了您的问题,则可以将将函数结果分配给变量:

/* in some script */

function someFunction(action) {
   console.log('triggered');
   return 'Received';
}

/* in another script and another level */
var returned = `location.href='${someFunction()}'`;

// Is it possible to get the returned value this way?
相关问题