如何获取js文件的GET参数

huangapple go评论62阅读模式
英文:

How to get js file GET params

问题

我需要获取由外部服务传递给JS文件的参数(我无法编辑加载逻辑)或JS脚本文件的URL。

例如,我的脚本通过URL加载:/widgets/<code>/<version>/script.js?v=<version>(版本相同)

与之相关的最大问题是页面上可能会出现许多这样的脚本(多达100-150个)。因此,您需要获取当前连接的脚本的URL或参数。

第二个大问题是脚本是不使用脚本标记加载的(该服务使用RequireJS)。

因此,例如,这个答案不相关。
https://stackoverflow.com/questions/1706571/how-can-i-get-url-of-js-file-in-same-js-file

在输出中,您需要获取<version>

英文:

I need to get a params passed to JS file by an external service (I can't edit loading logic) or URL of JS script file.

For example, my script is loading by URL: /widgets/<code>/<version>/script.js?v=<version>
(version are the same)

The biggest problem associated with the fact that a lot of such scripts can appear on the page (Up to 100-150 pieces). Accordingly, you need to get the URL or parameters of the script that is currently connected

The second big problem is that scripts are loaded without using the script tag. (The service uses RequireJS).

Therefore, this answer, for example, is not relevant.
https://stackoverflow.com/questions/1706571/how-can-i-get-url-of-js-file-in-same-js-file

At the output, you need to get <version>

答案1

得分: 2

以下是翻译好的部分:

如果您正在使用requirejs作为加载程序,可以按照以下方式操作:

  1. 在需要加载的每个模块中实现一个setVersion(version)函数。

  2. 使用requirejs的回调来调用setVersion()

requirejs(["foo/2.0/script.js"], foo => {
    // 在加载模块foo后调用此函数
    foo.setVersion("2.0");
})

如果您无法修改加载逻辑(即无法调整回调),那么您几乎没有机会。在这种情况下,无法从脚本内部获取URL的任何信息,因为在通过requirejs加载和评估脚本时,它只是一个普通的字符串,不知道它来自哪里...

英文:

If you are using requirejs as loader you can do as follows

  1. Implement a setVersion(version) function in each of the modules you need to load

  2. Use the callback of requirejs to call that setVersion()

    requirejs(["foo/2.0/script.js"], foo => {
      //this is called after the module foo is loaded
      foo.setVersion("2.0");
    })
    

If you cannot modify the loading logic at all (ie adapt the callback) you are pretty much out of luck. Then there is no way of getting anything from the url from within the script. Because at the moment your script is loaded and evaluated by requirejs it's just an ordinary string which doesn't know where it came from ...

huangapple
  • 本文由 发表于 2023年3月7日 16:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定