首页 > 解决方案 > 从 location.href="javascript:someFunction()" 获取价值?

问题描述

是否可以通过触发该函数来获取函数返回的值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?

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

感谢您的友好答复。

编辑:

顶级页面:

function someFunction() {
   var collectionEvent = new CustomEvent("PageEvent", {detail: {data:lotsOfData}});
   window.dispatchEvent(collectionEvent);
}

沙盒:

var data;
window.addEventListener("PageEvent", function(event) {
    data = event.detail.lotsOfData;
}, false);

到目前为止一切顺利,现在我可以触发:

window.href = "javascript:someFunction()";
setTimeOut(function() {
   doTheMainFunction(data);
}, 2000);

这是我不喜欢的工作,因为我不知道 someFunction 从主窗口对象获取数据并传递给沙箱需要多少时间,所以我无法做出承诺。

谢谢。

标签: javascript

解决方案


如果我很好地理解了你的问题,那么你可以将函数的结果存储到一个变量中:

/* 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?

推荐阅读