javascript - 从 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 从主窗口对象获取数据并传递给沙箱需要多少时间,所以我无法做出承诺。
谢谢。
解决方案
如果我很好地理解了你的问题,那么你可以将函数的结果存储到一个变量中:
/* 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?
推荐阅读
- java - 无法从源代码构建 open jdk 8, ubuntu 18.04, 64bit
- firebase - 监控 Firebase 存储更改的最佳方式
- parquet - Parquet-mr java 库的文档
- avd - 我的电脑不支持HAXM,有什么替代方案吗?
- scala - log4j 警告:找不到记录器的附加程序(org.apache.kafka.clients.producer.ProducerConfig)
- oauth-2.0 - LinkedIn OAuth2.0 使会话无效/强制重新授权
- python - 使用具有 2 个主键模型的基于类的视图 UpdateView
- r - 基于多列检索唯一记录的数据框
- javascript - Webpack Bundle 文件没有 CSS 样式和 UI 组件
- azure - Azure SQL 数据库 - 禁用 SQL Server 身份验证模式