简体   繁体   中英

How to pass javascript variable to script embed tag

I have a script which I am struggling with:

It does two things

  1. Takes the variable parameter from a URL
  2. Adds the parameter as a variable in a script embed tag

Number one works and I have been testing it with an iframe and I am able to pass the variable as the source code.

Number two does not work for script tags here is a snippet of the code

Heres the code I have to collect the variable from the url

// Parse the URL parameter
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g,"\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Give the parameter a variable name



var myvariable = getParameterByName('variable');

 $('#myvariable').html(myvariable);

I now want to pass myvariable to the javascript

<div id="otEmbedContainer" style="width:800px; height:640px"></div> <script src="https://exmaple.com/embed/embed/ot-embed.js?embedId=number&variable=myvariable"></script>

Any ideas would be great.

Thanks

Amended code doesnt seem to work

<script type="text/javascript">
// Parse the URL parameter
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g,"\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Give the parameter a variable name



var myvariable = getParameterByName('variable');

$('#myvariable').html(variable);

function addScript( src, value ) { var s = document.createElement( 'script' ); s.setAttribute( 'src', ' https://exmaple.com/embed/embed/ot-embed.js?embedId=number&variable= ' ); s.setAttribute( 'myvalue', myId); document.body.appendChild( s ); }

addScript("s");

You can't pass the values from the URL, but if the value is defined, you can pass it to your javascript using the attribute

<div id="otEmbedContainer" style="width:800px; height:640px"></div> 
<script src="https://exmaple.com/embed/embed/ot-embed.js?embedId=number" myvalue="1234"></script>

And then in your javascript, you can get the value using:

document.currentScript.getAttribute('myvalue'); //1234

Update

Now, when you are retrieving the value at runtime from the URL, you need to dynamically load the JS too. Remove the script from your HTML, once you have the value from your URL, then create a script and add it to HTML

function addScript( src, value ) {
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', src );
    s.setAttribute( 'myvalue', value);
    document.body.appendChild( s );
}

Call the function given above with your source link and the value which you need to pass to JS.

Example:

Your HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Dynamic JS example</title>
    </head>
    <body>
        <button onclick="load();">Load JS and show value from URL</button>
    </body>
    <script>
        var load = function(){
            var url = new URL(window.location.href);
            var value = url.searchParams.get("value");

            var s = document.createElement("script")
            s.setAttribute("src", "./test.js");
            s.setAttribute("value", value);
            document.body.appendChild(s);
        }
    </script>
</html>

Your JS

value = document.currentScript.getAttribute('value');
alert(value);

Load the HTML in the browser, pass the value in URL ?value=yeah and click on the button to see the magic.

IF you want to read the parameter from within the same script, you can get the last script tag and read the src from it.

var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length - 1];

function parseQueryString(src) {
    var query = src.split('?').pop();
    var params = query.split('&');
    var result = {};

    for (var i = 0; i < params.length; i++) {
        var parts = params[i].split('=');
        result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
    }

    return result;
}

console.log(parseQueryString(lastScript.src))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM