Javascript 如何将参数传递给 Script 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5292372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:31:05  来源:igfitidea点击:

How to pass parameters to a Script tag?

javascriptparameterswidgetxssscript-tag

提问by Tomer Lichtash

I read the tutorial DIY widgets - How to embed your site on another sitefor XSS Widgets by Dr. Nic.

我阅读了教程DIY widgets - How to embed your site on another sitefor XSS Widgets by Dr. Nic。

I'm looking for a way to pass parameters to the script tag. For example, to make the following work:

我正在寻找一种将参数传递给脚本标记的方法。例如,要进行以下工作:

<script src="http://path/to/widget.js?param_a=1&amp;param_b=3"></script>

Is there a way to do this?

有没有办法做到这一点?



Two interesting links:

两个有趣的链接:

采纳答案by Tomer Lichtash

Got it. Kind of a hack, but it works pretty nice:

知道了。有点像黑客,但效果很好:

var params = document.body.getElementsByTagName('script');
query = params[0].classList;
var param_a = query[0];
var param_b = query[1];
var param_c = query[2];

I pass the params in the script tag as classes:

我将脚本标签中的参数作为类传递:

<script src="http://path.to/widget.js" class="2 5 4"></script>

This articlehelped a lot.

这篇文章很有帮助。

回答by Richard Fox

I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.

我为回答一个超级老问题而道歉,但在与上述解决方案搏斗了一个小时后,我选择了更简单的东西。

<script src=".." one="1" two="2"></script>

Inside above script:

在上面的脚本中:

document.currentScript.getAttribute('one'); //1
document.currentScript.getAttribute('two'); //2

Much easier than jquery OR url parsing.

比jquery OR url解析容易得多。

You might need the polyfil for doucment.currentScript from @Yared Rodriguez's answer for IE:

您可能需要来自@Yared Rodriguez 对 IE 的回答中的 doucment.currentScript 的 polyfil:

document.currentScript = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  return scripts[scripts.length - 1];
})();

回答by OBender

It's better to Use feature in html5 5 data Attributes

最好在 html5 5 数据属性中使用功能

<script src="http://path.to/widget.js" data-width="200" data-height="200">
</script>

Inside the script file http://path.to/widget.jsyou can get the paremeters in that way:

在脚本文件http://path.to/widget.js 中,您可以通过这种方式获取参数:

<script>
function getSyncScriptParams() {
         var scripts = document.getElementsByTagName('script');
         var lastScript = scripts[scripts.length-1];
         var scriptName = lastScript;
         return {
             width : scriptName.getAttribute('data-width'),
             height : scriptName.getAttribute('data-height')
         };
 }
</script>

回答by Eric Leschinski

JQuery has a way to pass parameters from HTML to javascript:

JQuery 有一种方法可以将参数从 HTML 传递到 javascript:

Put this in the myhtml.htmlfile:

把它放在myhtml.html文件中:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.jsfile and put this in there:

在同一目录中创建一个subscript.js文件并将其放在那里:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

分析结果:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

加载 myhtml.html 页面将 'foobar.mp4' 打印到屏幕上。名为 video_filename 的变量从 html 传递到 javascript。Javascript 将它打印到屏幕上,它显示为嵌入到父级的 html 中。

jsfiddle proof that the above works:

jsfiddle 证明上述方法有效:

http://jsfiddle.net/xqr77dLt/

http://jsfiddle.net/xqr77dLt/

回答by Robidu

Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:

另一种方法是使用元标记。任何应该传递给 JavaScript 的数据都可以像这样分配:

<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />

The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):

然后可以像这样从元标记中提取数据(最好在 DOMContentLoaded 事件处理程序中完成):

var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;

Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...

使用 jQuery 或类似工具绝对没有麻烦,不需要任何技巧和变通方法,并且可以与任何支持元标记的 HTML 版本一起使用...

回答by rg88

If you are using jquery you might want to consider their data method.

如果您使用 jquery,您可能需要考虑他们的数据方法。

I have used something similar to what you are trying in your response but like this:

我使用了类似于您在回复中尝试的内容,但如下所示:

<script src="http://path.to/widget.js" param_a = "2" param_b = "5" param_c = "4">
</script>

You could also create a function that lets you grab the GET params directly (this is what I frequently use):

您还可以创建一个函数,让您直接获取 GET 参数(这是我经常使用的):

function $_GET(q,s) {
    s = s || window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}

// Grab the GET param
var param_a = $_GET('param_a');

回答by Yared Rodriguez

it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.

这是一个非常古老的线程,我知道但是如果有人在寻找解决方案后到达这里,这也可能有所帮助。

Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:

基本上,我使用 document.currentScript 从我的代码运行的位置获取元素,并使用我正在寻找的变量的名称进行过滤。我使用名为“get”的方法扩展了 currentScript,因此我们将能够使用以下方法获取该脚本中的值:

document.currentScript.get('get_variable_name');

In this way we can use standard URI to retrieve the variables without adding special attributes.

通过这种方式,我们可以使用标准 URI 来检索变量,而无需添加特殊属性。

This is the final code

这是最终的代码

document.currentScript.get = function(variable) {
    if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
    return decodeURIComponent(variable[1]);
};

I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:

我忘记了 IE :) 再简单不过了...好吧我没有提到 document.currentScript 是一个 HTML5 属性。它没有被包含在不同版本的 IE 中(我测试到 IE11,它还没有)。为了 IE 兼容性,我在代码中添加了这部分:

document.currentScript = document.currentScript || (function() {
  var scripts = document.getElementsByTagName('script');
  return scripts[scripts.length - 1];
})();

What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.

我们在这里做的是为IE定义一些替代代码,它返回当前的脚本对象,在解决方案中需要从src属性中提取参数。这不是 IE 的完美解决方案,因为存在一些限制;如果脚本是异步加载的。较新的浏览器应包含“.currentScript”属性。

I hope it helps.

我希望它有帮助。

回答by gagallo7

Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.

多亏了 jQuery,一个简单的 HTML5 兼容解决方案是创建一个额外的 HTML 标签,如 div,来存储数据。

HTML:

HTML:

<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
  <button id='clickButton'>Click me</button>
</div>

JavaScript:

JavaScript:

$(document).ready(function() {
    var fetchData = $("#dataDiv").data('arg1') + 
                    $("#dataDiv").data('arg2') ;

    $('#clickButton').click(function() {
      console.log(fetchData);
    })
});

Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0

使用上述代码进行现场演示:http: //codepen.io/anon/pen/KzzNmQ?editors=1011#0

On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.

在现场演示中,可以看到 HTML5 data-* 属性中的数据被连接并打印到日志中。

Source: https://api.jquery.com/data/

来源:https: //api.jquery.com/data/

回答by bwest

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

将您需要的值放在其他脚本可以检索它们的地方,例如隐藏输入,然后在初始化新脚本时从它们的容器中提取这些值。您甚至可以将所有参数作为 JSON 字符串放入一个隐藏字段中。

回答by Fom

I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScriptor the data attributesmethod would be most stylish.

我想要尽可能多地支持旧浏览器的解决方案。否则我会说currentScriptdata 属性方法将是最时尚的。

This is the only of these methods not brought up here yet. Particularly, if for some reason you have great amounts of data, then the best option might be:

这是这些方法中唯一没有在这里提出的方法。特别是,如果由于某种原因您有大量数据,那么最好的选择可能是:

localStorage

本地存储

/* On the original page, you add an inline JS Script: */
<script>
   localStorage.setItem('data-1', 'I got a lot of data.');
   localStorage.setItem('data-2', 'More of my data.');
   localStorage.setItem('data-3', 'Even more data.');
</script>

/* External target JS Script, where your data is needed: */
var data1 = localStorage.getItem('data-1');
var data2 = localStorage.getItem('data-2');
var data3 = localStorage.getItem('data-3');

localStorage has full modern browser support, and surprisingly good support of older browsers too, back to IE 8, Firefox 3,5 and Safari 4 [eleven years back] among others.

localStorage 具有完整的现代浏览器支持,并且对旧浏览器的支持也出奇的好,回到 IE 8、Firefox 3,5 和 Safari 4 [11 年前] 等。

If you don't have a lot of data, but still want extensive browser support, maybe the best option is:

如果您没有大量数据,但仍需要广泛的浏览器支持,也许最好的选择是:

Meta tags [by Robidu]

元标签 [by Robidu]

/* HTML: */
<meta name="yourData" content="Your data is here" />

/* JS: */
var data1 = document.getElementsByName('yourData')[0].content;

The flaw of this, is that the correct place to put meta tags [up until HTML 4] is in the head tag, and you might not want this data up there. To avoid that, or putting meta tags in body, you could use a:

这样做的缺陷是,放置元标记 [直到 HTML 4] 的正确位置是在 head 标记中,而您可能不希望这些数据放在那里。为避免这种情况,或将元标记放在正文中,您可以使用:

Hidden paragraph

隐藏段落

/* HTML: */
<p hidden id="yourData">Your data is here</p>

/* JS: */
var yourData = document.getElementById('yourData').innerHTML;

For even more browser support, you could use a CSS class instead of the hidden attribute:

为了获得更多浏览器支持,您可以使用 CSS 类而不是 hidden 属性:

/* CSS: */
.hidden {
   display: none;
}

/* HTML: */
<p class="hidden" id="yourData">Your data is here</p>