在非内联脚本方法中获取内联脚本的脚本元素

  • 本文关键字:脚本 元素 获取 方法 javascript
  • 更新时间 :
  • 英文 :


我有一个内联脚本,比如inline.html和一个不内联的库library.js

在内联脚本中,我调用library.method(),在这个方法中,我需要知道该方法是从哪个内联脚本中调用的。

library.method = function() {
document.currentScript;
};

当然给出了库的脚本元素。

但我需要调用脚本的脚本元素:例如document.invokingScript。(我知道,这是不存在的(。

我能做点什么吗?

出于可读性的原因,我不想在内联脚本中执行library.method(document.currentScript)

如果您可以保证只从函数内部调用library.method,并且这个包装函数在每个内联脚本中都有不同的名称,那么您可以使用以下代码段(取自https://gist.github.com/irisli/716b6dacd3f151ce2b7e)

var stackTrace = (new Error()).stack; // Only tested in latest FF and Chrome
var callerName = stackTrace.replace(/^Errors+/, ''); // Sanitize Chrome
callerName = callerName.split("n")[1]; // 1st item is this, 2nd item is caller
callerName = callerName.replace(/^s+at Object./, ''); // Sanitize Chrome
callerName = callerName.replace(/ (.+)$/, ''); // Sanitize Chrome
callerName = callerName.replace(/@.+/, ''); // Sanitize Firefox

最新更新