Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable to Javascript directly from <script> HTML tag

Is it possible to pass a variable directly from the HTML tag <script>:

<script async src="https://example.com/lib.js" site="test.com"></script>

such that lib.js can access site like a regular variable?

like image 834
Basj Avatar asked Dec 21 '20 13:12

Basj


People also ask

Can I pass a variable from HTML to JavaScript?

Use the onclick attribute in a button tag with the function name and pass value in this function. With this method, you can also take input from users and pass parameters in the JavaScript function from HTML.

How do you pass a variable in HTML script?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

How do you pass a value in a script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.


1 Answers

<script async src="https://example.com/lib.js" site="sitePath"></script>

and:

site = document.currentScript.getAttribute('site'); // sitePath
like image 197
Olaru Alina Avatar answered Oct 07 '22 00:10

Olaru Alina