Programing

스크립트 태그에 매개 변수를 전달하는 방법은 무엇입니까?

lottogame 2020. 11. 13. 07:43
반응형

스크립트 태그에 매개 변수를 전달하는 방법은 무엇입니까?


튜토리얼 DIY 위젯 -Dr. Nic의 XSS 위젯을 위해 다른 사이트사이트를 삽입하는 방법을 읽었습니다 .

스크립트 태그에 매개 변수를 전달하는 방법을 찾고 있습니다. 예를 들어, 다음 작업을 수행하려면 :

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

이를 수행하는 방법이 있습니까?


두 가지 흥미로운 링크 :


나는 매우 오래된 질문에 답한 것에 대해 사과하지만 위의 솔루션으로 레슬링 한 시간을 보낸 후 더 간단한 것을 선택했습니다.

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

위 스크립트 내부 :

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

jquery 또는 URL 구문 분석보다 훨씬 쉽습니다.

IE에 대한 @Yared Rodriguez의 답변에서 doucment.currentScript에 대한 polyfil이 필요할 수 있습니다.

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

HTML5 5 데이터 속성 에서 기능을 사용하는 것이 더 좋습니다.

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

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>

알았다. 일종의 해킹이지만 꽤 잘 작동합니다.

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];

스크립트 태그의 매개 변수를 클래스로 전달합니다.

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

이 기사 는 많은 도움 되었습니다.


JQuery에는 HTML에서 자바 스크립트로 매개 변수를 전달하는 방법이 있습니다.

이것을 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>

같은 디렉토리에 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);

결과 분석 :

myhtml.html 페이지를로드하면 'foobar.mp4'가 화면에 인쇄됩니다. video_filename이라는 변수가 html에서 javascript로 전달되었습니다. Javascript는 그것을 화면에 인쇄했고 부모의 html에 포함 된 것처럼 보였습니다.

위의 내용이 작동한다는 jsfiddle 증명 :

http://jsfiddle.net/xqr77dLt/


또 다른 방법은 메타 태그를 사용하는 것입니다. JavaScript로 전달되어야하는 데이터는 다음과 같이 할당 할 수 있습니다.

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

그런 다음 다음과 같이 메타 태그에서 데이터를 가져올 수 있습니다 (DOMContentLoaded 이벤트 핸들러에서 가장 잘 수행됨).

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

jQuery 또는 그와 비슷한 것들이 전혀 번거롭지 않으며, 해킹과 해결 방법이 필요하지 않으며, 메타 태그를 지원하는 모든 HTML 버전에서 작동합니다.


jquery를 사용하는 경우 데이터 방법 을 고려할 수 있습니다 .

나는 당신이 당신의 응답에서 시도하는 것과 비슷한 것을 사용했지만 다음과 같습니다.

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

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');

jQuery 덕분에 간단한 HTML5 호환 솔루션은 div와 같은 추가 HTML 태그를 만들어 데이터를 저장하는 것입니다.

HTML :

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

자바 스크립트 :

$(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

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

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


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('get_variable_name');

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

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:

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.

I hope it helps.


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.


Create an attribute that contains a list of the parameters, like so:

<script src="http://path/to/widget.js" data-params="1, 3"></script>

Then, in your JavaScript, get the parameters as an array:

var script = document.currentScript || 
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();

var params = (script.getAttribute('data-params') || '').split(/, */);

params[0]; // -> 1
params[1]; // -> 3

I wanted solutions with as much support of old browsers as possible. Otherwise I'd say either the currentScript or the data attributes method would be most stylish.

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.

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

Meta tags [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:

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 {
   display: none;
}

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

참고URL : https://stackoverflow.com/questions/5292372/how-to-pass-parameters-to-a-script-tag

반응형