JavaScript 파일에 매개 변수 전달
종종 웹 페이지에 특정 변수를 정의해야 하는 사용할 JavaScript 파일이 있습니다.
코드는 다음과 같습니다.
<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
var obj1 = "somevalue";
</script>
하지만 제가 하고 싶은 것은:
<script type="text/javascript"
src="file.js?obj1=somevalue&obj2=someothervalue"></script>
여러 가지 방법을 시도해 보았지만 가장 좋은 방법은 다음과 같이 쿼리 문자열을 구문 분석하는 것입니다.
var scriptSrc = document.getElementById("myscript").src.toLowerCase();
그런 다음 내 가치관을 검색합니다.
제 문자열을 구문 분석하는 기능을 구축하지 않고 이를 수행할 수 있는 다른 방법이 있는지 궁금합니다.
여러분은 다른 방법들을 알고 있나요?
가능하면 글로벌 변수를 사용하지 않는 것이 좋습니다.네임스페이스와 OOP를 사용하여 인수를 개체로 전달합니다.
이 코드는 file.js:
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
alert('Hello World! -' + _args[0]);
}
};
}());
html 파일에는 다음이 있습니다.
<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["somevalue", 1, "controlId"]);
MYLIBRARY.helloWorld();
</script>
임의 특성을 가진 매개 변수를 전달할 수 있습니다.이 기능은 모든 최신 브라우저에서 작동합니다.
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
일부 file.js 내에서 전달된 변수 값을 다음과 같이 가져올 수 있습니다.
........
var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..
var my_var_1 = this_js_script.attr('data-my_var_1');
if (typeof my_var_1 === "undefined" ) {
var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value
var my_var_2 = this_js_script.attr('data-my_var_2');
if (typeof my_var_2 === "undefined" ) {
var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value
...등...
제가 우연히 발견한 또 다른 아이디어는 한 명의 학생들에게 할당하는 것입니다.id
에▁<script>
및를 "" " " " "로 전달data-*
특성.그 결과<script>
태그는 다음과 같이 보입니다.
<script id="helper" data-name="helper" src="helper.js"></script>
그런 다음 스크립트는 id를 사용하여 프로그래밍 방식으로 자신을 찾고 인수를 구문 분석할 수 있습니다.의 의경우앞이 때<script>
과 같이 할 수 .
var name = document.getElementById("helper").getAttribute("data-name");
는 리는우를 받습니다.name
=helper
이 URL을 확인하십시오.그것은 요구 사항에 완벽하게 작동하고 있습니다.
http://feather.elektrum.org/book/src.html
작가님께 감사드립니다.빠른 참조를 위해 아래에 주요 논리를 붙여 넣었습니다.
var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
var params = parseQuery( queryString );
function parseQuery ( query ) {
var Params = new Object ();
if ( ! query ) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) continue;
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
전역 변수 :-D를 사용합니다.
다음과 같이:
<script type="text/javascript">
var obj1 = "somevalue";
var obj2 = "someothervalue";
</script>
<script type="text/javascript" src="file.js"></script">
'는 'file.js'의 JavaScript에 수 .obj1
그리고.obj2
EDIT 'file.js'가 확인을 원할 경우 추가하고 싶습니다.obj1
그리고.obj2
심지어 다음 기능을 사용할 수 있다고 선언했습니다.
function IsDefined($Name) {
return (window[$Name] != undefined);
}
이게 도움이 되길 바랍니다.
여기 매우 급하게 개념 증명이 있습니다.
적어도 2곳은 개선이 가능한 곳이 있을 것이고, 야생에서 이것이 오래 살아남지 못할 것이라고 확신합니다.보다 유용하고 유용하게 사용할 수 있도록 피드백을 제공하는 것은 환영합니다.
핵심은 스크립트 요소의 ID를 설정하는 것입니다.유일한 단점은 쿼리 문자열을 풀할 ID를 찾기 때문에 스크립트를 한 번만 호출할 수 있다는 것입니다.대신 스크립트가 모든 쿼리 요소를 순환하여 해당 요소 중 하나가 해당 요소를 가리키는지 확인하고, 해당 요소의 마지막 인스턴스를 사용하는 경우 이 문제가 해결될 수 있습니다.어쨌든, 코드를 계속합니다.
호출 중인 스크립트:
window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;
//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");
//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);
//Next split the querystring into array
var params = queryString.split("&");
//Next loop through params
for(var i = 0; i < params.length; i++){
var name = params[i].substring(0,params[i].indexOf("="));
var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);
//Test if value is a number. If not, wrap value with quotes:
if(isNaN(parseInt(value))) {
params[i] = params[i].replace(value, "'" + value + "'");
}
// Finally, use eval to set values of pre-defined variables:
eval(params[i]);
}
//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};
다음 페이지를 통해 호출된 스크립트:
<script id="myScript" type="text/javascript"
src="test.js?header=Test Page&text=This Works"></script>
<h1 id="docTitle"></h1>
<p id="docText"></p>
매우 단순할 수 있습니다.
예를들면
<script src="js/myscript.js?id=123"></script>
<script>
var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>
그런 다음 아래와 같이 쿼리 문자열을 json으로 변환할 수 있습니다.
var json = $.parseJSON('{"'
+ queryString.replace(/&/g, '","').replace(/=/g, '":"')
+ '"}');
그리고 나서 다음과 같이 사용할 수 있습니다.
console.log(json.id);
jQuery와 같은 Javascript 프레임워크를 사용하는 경우 이 작업을 쉽게 수행할 수 있습니다.이렇게.
var x = $('script:first').attr('src'); //Fetch the source in the first script tag
var params = x.split('?')[1]; //Get the params
이제 변수 매개 변수로 분할하여 이러한 매개 변수를 사용할 수 있습니다.
프레임워크 없이 동일한 프로세스를 수행할 수 있지만 코드 행이 더 필요합니다.
HTML:
<script src='greet.js' data-param1='hello' data-param2='world'></script>
// greet.js:
const prm1=document.currentScript.dataset.param1;
const prm2=document.currentScript.dataset.param2;
스크립트 언어를 사용하여 자바스크립트 파일을 작성하고, 모든 요청에 따라 파일에 변수를 삽입할 수 있습니다.웹 서버에 js-file을 정적으로 배포하지 않도록 지시해야 합니다(mod_rewrite를 사용하면 충분합니다).
이러한 js 파일은 지속적으로 변경되므로 캐시가 손실됩니다.
안녕.
유효한 html은 아니지만 웹 페이지에 스크립트 태그에 대한 사용자 지정 특성을 만들면 작동하는 것 같습니다.
<script id="myScript" myCustomAttribute="some value" ....>
그런 다음 Javascript의 사용자 지정 특성에 액세스합니다.
var myVar = document.getElementById( "myScript" ).getAttribute( "myCustomAttribute" );
이것이 스크립트 원본 문자열을 구문 분석하는 것보다 나은지 나쁜지 확실하지 않습니다.
여기서 저는 이와 같은 일을 하는 다른 방법을 찾았습니다.필요한 js 파일 [테스트에 사용한 것처럼 cttricks.js, 임의의 .js 파일을 가질 수 있습니다]에서는 모든 스크립트 요소를 나열하고 항상 마지막 인덱스에 있으므로 필요한 요소를 가져옵니다.그런 다음 여기서 ".attributes.src.value"를 가져옵니다.
자, 어떤 경우든, 스크립트 호출은,
<script src="./cttricks.js?data1=Hello&data2=World"></script>
그리고 cttricks.js 스크립트 파일에서
var scripts = document.getElementsByTagName('script');
var jsFile = new URL("http://" + scripts[scripts.length-1].attributes.src.value);
/*get value from query parameters*/
console.log(jsFile.searchParams.get("data1"));
console.log(jsFile.searchParams.get("data2"));
맛있게 드세요!!
아니요, JS 파일 URL의 쿼리 문자열 부분에 변수를 추가하여 이를 수행할 수 없습니다. 만약 그것이 당신을 괴롭히는 문자열을 구문 분석하기 위해 코드 부분을 쓴다면, 아마도 다른 방법은 Json이 당신의 변수를 인코딩하여 태그의 rel 속성과 같은 것에 넣는 것입니까?저는 이것이 HTML 검증 측면에서 얼마나 타당한지 모르겠습니다, 만약 그것이 당신이 매우 걱정하는 것이라면.그런 다음 스크립트의 rel 속성을 찾은 다음 json_decode를 수행하면 됩니다.
예를 들어
<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>
좋은 질문과 창의적인 답변이지만 저는 당신의 방법을 매개 변수화하는 것이 좋습니다. 그러면 속임수 없이 당신의 모든 문제를 해결할 수 있을 것입니다.
기능이 있는 경우:
function A()
{
var val = external_value_from_query_string_or_global_param;
}
다음으로 변경할 수 있습니다.
function B(function_param)
{
var val = function_param;
}
이것이 가장 자연스러운 접근 방식이라고 생각합니다. '파일 매개 변수'에 대한 추가 문서를 작성할 필요가 없으며 동일한 정보를 받을 수 있습니다.이 기능은 다른 개발자가 사용자의 js 파일을 사용하도록 허용하는 경우 특히 유용합니다.
CSP 검사(안전하지 않은 인라인 검사를 금지함)를 통과하는 방법이 필요한 경우, nonce 메서드를 사용하여 스크립트와 CSP 지침에 고유한 값을 추가하거나 HTML에 값을 기록한 후 다시 읽어야 합니다.
express.js에 대한 Nonce 메서드:
const uuidv4 = require('uuid/v4')
app.use(function (req, res, next) {
res.locals.nonce = uuidv4()
next()
})
app.use(csp({
directives: {
scriptSrc: [
"'self'",
(req, res) => `'nonce-${res.locals.nonce}'` // 'nonce-614d9122-d5b0-4760-aecf-3a5d17cf0ac9'
]
}
}))
app.use(function (req, res) {
res.end(`<script nonce="${res.locals.nonce}">alert(1 + 1);</script>`)
})
또는 html 메서드에 값을 씁니다.이 경우 Jquery를 사용합니다.
<div id="account" data-email="{{user.email}}"></div>
...
$(document).ready(() => {
globalThis.EMAIL = $('#account').data('email');
}
이 질문이 얼마 전에 제기되었지만, 오늘날에도 여전히 관련이 있습니다.스크립트 파일 매개 변수를 사용하는 간단한 방법은 아니지만, 이러한 방법이 가장 적합한 몇 가지 극단적인 사용 사례가 이미 있습니다.
저는 제가 조금 전에 썼던 것보다 더 나은 해결책을 찾기 위해 이 게시물을 우연히 발견했고, 아마도 네이티브 기능이나 비슷한 것을 찾을 수 있기를 희망했습니다.
더 나은 솔루션이 구현될 때까지 솔루션을 공유하겠습니다.이것은 대부분의 최신 브라우저에서 작동하며, 오래된 브라우저에서도 작동하지 않았습니다.
위의 모든 솔루션은 사전 정의되고 잘 표시된 SCRIPT 태그를 주입해야 하며 HTML 구현에 전적으로 의존해야 한다는 사실에 기초합니다.하지만 스크립트가 동적으로 주입되거나 더 나쁜 것은 다양한 웹사이트에서 사용될 라이브러리를 쓴다면 어떨까요?
이러한 경우와 일부 다른 경우에는 위의 모든 답변이 충분하지 않고 심지어 너무 복잡해집니다.
먼저, 여기서 무엇을 달성해야 하는지 이해해 보겠습니다.우리가 해야 할 일은 스크립트 자체의 URL을 가져오는 것입니다. 거기서부터는 식은 죽 먹기입니다.
실제로 스크립트 자체에서 스크립트 URL을 가져오는 좋은 방법이 있습니다. 네브기 중하능나의 중 Error
class는 마지막 호출에 대한 정확한 파일 추적을 포함하여 "문제가 있는 위치"의 스택 추적을 제공하는 기능입니다.이를 위해 Error 인스턴스의 스택 속성을 사용하여 생성된 후 전체 스택 추적을 제공합니다.
마법의 원리는 다음과 같습니다.
// The pattern to split each row in the stack trace string
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
// For browsers, like Chrome, IE, Edge and more.
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
// For browsers, like Firefox, Safari, some variants of Chrome and maybe other browsers.
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?@)?(.*?):\d+(?::\d+)?$/;
const getFileParams = () => {
const stack = new Error().stack;
const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
if (!url) {
console.warn("Something went wrong. You should debug it and find out why.");
return;
}
try {
const urlObj = new URL(url);
return urlObj.searchParams; // This feature doesn't exists in IE, in this case you should use urlObj.search and handle the query parsing by yourself.
} catch (e) {
console.warn(`The URL '${url}' is not valid.`);
}
}
OP 사례와 같이 스크립트 호출의 경우:
<script type="text/javascript" src="file.js?obj1=somevalue&obj2=someothervalue"></script>
에서file.js
스크립트, 이제 다음을 수행할 수 있습니다.
const params = getFileParams();
console.log(params.get('obj2'));
// Prints: someothervalue
이는 Require에서도 작동합니다.JS 및 기타 동적으로 주입된 파일 스크립트.
javascript가 포함된 페이지에서 localStorage를 사용하고 javascript 자체 안에서 다시 사용하는 것이 훨씬 더 좋고 현대적인 해결책이라고 생각합니다.다음을 사용하여 localStorage에서 설정:
localStorage.setItem("nameOfVariable", "some text value");
Javascript 파일 내부에서 다음과 같이 참조합니다.
localStorage.getItem("nameOfVariable");
매개 변수를 js 모듈에 전달하고 다음을 통해 읽을 수 있습니다.import.meta.url
.
예를 들어, 다음 HTML을 사용하여
<script type="module">
import './index.mjs?someURLInfo=5';
</script>
다음 자바스크립트 파일은 일부를 기록할 것입니다.URLInfo 매개 변수:
// index.mjs
new URL(import.meta.url).searchParams.get('someURLInfo'); // 5
파일이 다른 파일을 가져올 때도 마찬가지입니다.
// index.mjs
import './index2.mjs?someURLInfo=5';
// index2.mjs
new URL(import.meta.url).searchParams.get('someURLInfo'); // 5
window.location의 백업과 함께 document.currentScript.src 사용
var url = new URL((document.currentScript.src)?document.currentScript.src:window.location.toLocaleString());
var obj1 = url.searchParams.get("obj1");// returns somevalue
언급URL : https://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files
'programing' 카테고리의 다른 글
c에서 함수에 대한 인수로 수신된 정수 배열의 크기 찾기 (0) | 2023.07.23 |
---|---|
복귀를 기다리는 약속과 복귀를 약속하는 약속의 차이 (0) | 2023.07.23 |
Python 2.7은 사용자 입력을 받고 인용문 없이 문자열로 조작합니다. (0) | 2023.07.23 |
각 연결된 항목의 개수와 함께 group_concat을 사용하는 SQL이 아니라 한 행의 총 개수입니다. (0) | 2023.07.23 |
mysql 어댑터 'gem install active record-mysql-adapter'를 설치하십시오. (0) | 2023.07.23 |