Javascript append string dynamically to script element - javascript

How do I append the following variable within my html (as part of script tag).
var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';
I am getting an invalid token error with the below code;
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.innerHTML = "var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';";
$("body").append( script );

You need to escape the carriage returns. Also as #maxzoom suggests, you probably want to use innerText rather than innerHTML.
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = "var x = '-----BEGIN CERT\\nMIIDvTCCAqWgAsdfsdfTAktS\\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\\ncG1vcmdhbjER\\n-----END CERT-----\\n;'; console.log(x);";
$("body").append(script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here from the inspector is it working in action...

To handle embedded expressions such as new line character \n in a string you could use Template literals notation as below:
var script = document.createElement('script');
script.type = 'text/javascript';
var content = "var x = `-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n`;";
content += "console.log(x);";
script.innerHTML = content;
$("body").append(script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
When viewing generated source in browser the script is present in body element:

You should try this way:
var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;'
var script = `<script type="text/javascript">${x}</script>`
$("body").append(script);

Related

Google Custom Search is adding %20 in search URL and Query

I have created a google custom search for my website as below but when i search 2-3 keywords it replaces the spaces with %20 and shows no results:
Result Page and Query
Search Box Code:
<script>
(function() {
var cx = '44444:orudazwgyxa';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only></gcse:searchbox-only>
Search result code:
<script>
(function() {
var cx = '44444:orudazwgyxa';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only linktarget="_parent"></gcse:searchresults-only>
I don't want %20 in my query instead of spaces but i want to show the keywords as it is. And it should show the result for the searched keywords.
Thanks
It seems the solution to the bad results is taking the "www" out of our target URL for the results page.
Sounds goofy to me, but hey, it worked.
So, if anyone else is having the same problem, check your result page URL target and remove the www from it
So instead of: http://www.yourwebsite.com/search_results.html
use: http://yourwebsite.com/search_results.html
And, then it will work!

Insert a script tag before another specific script tag

I have these lines to call my JS files and libraries:
<script src="assets/libs/perfect-scrollbar/perfect-scrollbar.jquery.js"></script>
<script src="assets/libs/PACE/pace.min.js"></script>
<script src="assets/js/library.js"></script>
<script src="assets/js/plugins.js"></script>
<script src="assets/js/app.js"></script>
Dynamically, I need to insert a new library. So I would make:
document.body.appendChild(script);
Where script is my new library.
But how can I insert it just before library.js ?
Thanks for your help.
It is working , i did experiment on this and result is Positive. Try This code
var mynewScript = document.createElement("script");
mynewScript.type = "text/javascript";
mynewScript.src = "http://mywebsite.com";
var a = document.getElementsByTagName('script')[2]; // [2] is the index of library.js
var parentT = a.parentNode;
parentT.insertBefore(mynewScript , a);
<script src="assets/libs/perfect-scrollbar/perfect-scrollbar.jquery.js"></script>
<script src="assets/libs/PACE/pace.min.js"></script>
<script>
document.body.appendChild(script);
document.body.appendChild(<library.js file>);
document.body.appendChild(<plugins.js file>);
document.body.appendChild(<app.js file>);
</script>
Add the following scripts dynamically as well!
If you do not want to do this, then you'll have to fetch the DOM elements using $('html').html() in your script and use the technique mentioned here as suggested by #Liam.
BUT! If you want to load the above mentioned scripts after loading your new library, there has to be a reason for that (those scripts depend on that library), in which case you should add those scripts dynamically as well.
I did like this and its work correctly
const ID = 'test-snippet';
// abort if it already exists
if ( document.getElementById( ID ) ) {
return;
}
const scriptTags = document.getElementsByTagName( 'script' );
const lastScriptTag = scriptTags[scriptTags.length - 1];
// create new script element
const js = document.createElement( 'script' );
js.id = ID;
js.src = 'https://some.js/';;
js.type = 'text/javascript';
js.async = true;
// append it after the last script tag
lastScriptTag.parentNode.insertBefore( js, lastScriptTag );

How to make goal completion work on hashchange?

I have an AngularJS webapp where there are no separate pages.
I have set up a goal completion so that there's a code that is triggered by a javascript event,
and it has the following structure:
function call_completion(){
window.google_conversion_id = 973404965;
window.google_conversion_language = "en";
window.google_conversion_format = "1";
window.google_conversion_color = "ffffff";
window.google_conversion_label = "doGHCLPK2wkQpfaT0AM";
window.google_conversion_value = 1.000000;
window.google_remarketing_only = false;
var s = document.createElement('script');
s.type = "text/javascript";
s.src = '//www.googleadservices.com/pagead/conversion.js';
document.body.appendChild(s);
}
Yet, I can't see any completions registered in Google Analytics. What could be the problem?
Is this the correct way to do it? Is there perhaps some nifty plugin that gets this problem right?
UPDATE:
For the new Universal Analytics, there is a plugin called angular-ga.
It eliminates the whole question.
You shouldn't append the script to your view, since it won't be executed.
You should use this:
$.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
To get the script working on that page and execute it.
Hope this helps :)
The <noscript> part also has to be included.
Something like this:
$('body')
.append('\
<!-- Google Code for Subscriptions Conversion Page -->\n\
<script type="text/javascript">\n\
/* <![CDATA[ */\n\
var google_conversion_id = 973404965;\n\
var google_conversion_language = "en";\n\
var google_conversion_format = "1";\n\
var google_conversion_color = "ffffff";\n\
var google_conversion_label = "doGHCLPK2wkQpfaT0AM";\n\
var google_conversion_value = 1.000000;\n\
var google_remarketing_only = false;\n\
/* ]]> */\n\
</script>\
');
$('body')
.append('<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">')
.append($('<noscript>')
.append($('<div style="display:inline;">')
.append('<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/973404965/?value=1.000000&label=doGHCLPK2wkQpfaT0AM&guid=ON&script=0"/>')
)
);

Multiple Javascript Asynchronously Loading in a Page

<script type="text/javascript">
function loadScript(scriptpath) {
var s = document.getElementsByTagName('script')[0];
var ss = document.createElement('script');
ss.type = 'text/javascript';
ss.async = true;
ss.src = scriptpath;
s.parentNode.insertBefore(ss, s);
}
loadScript('compressed1.js');
loadScript('compressed2.js');
</script>
but i am getting error that SS is not defined can somebody help me with above coding?
var ssa
Keep variable names consistent. It's usually a good idea to give meaningful names like newScript

How to Change <script> id from with script - Javascript

I would like to change the id of a tag from within the external script it points to. What is the proper way of doing this?
Here is my script tag:
<script id="ID1" type="text/javascript" src="PATH_TO_EXTERNAL_JS"></script>
And here is what I'm trying to do from within my external script:
var sessionID = generateSessionID();
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
script.id = script.id + "_" + sessionID;
However, when I look at the live DOM tree in firebug, i see 2 scripts referenced in the DOM. One with the original ID, and one with the new ID.
Thanks!
Use setAttribute
script.setAttribute("id", script.id + "_" + sessionID);
I think You should modify Your code, to somewhat like this:
var i = 0
var sessionID = generateSessionID();
var scripts = document.getElementsByTagName('script');
var script = null;
for (i = 0; i < scripts.length; i++)
if (scripts[i].src.toString() == 'PATH_TO_EXTERNAL_JS'){
script = scripts[i];
break;
}
if (script)
script.id = script.id + "_" + sessionID;
In other words. Get all the SCRIPT elements, iterate through this collection to look for an element that has some known attribute (src in this example) and if it's found, set it's new id.
You need to remove the old script, if your going to do it that way. Although Mike Lewis answer has a better method.
document.removeChild(originalScript)

Categories