I am using an mvc application and in _Layout.cshtml page I have some javascript I wanna pass it a value of
System.Configuration.ConfigurationManager.AppSettings["anID"].ToString()
here
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount',PASS THAT HERE!]);
How do I do this? I am not sure how to pass data to javascript??
You could try like this:
<%
var value = System.Configuration.ConfigurationManager.AppSettings["anID"].ToString();
%>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', <%= value %>]);
</script>
or with the Razor view engine:
#{
var value = System.Configuration.ConfigurationManager.AppSettings["anID"].ToString();
}
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', #value]);
</script>
In situations where you have more javascript than that, and are keeping it in a separate file from the view, you can also do this:
<script type="text/javascript">
var _anId = #System.Configuration.ConfigurationManager.AppSettings["anID"].ToString();
var _somethingElseNeededInJsFile = #Model.SomethingNeeded;
</script>
Then in the separate javascript file, you can reference the variables easily.
var _gaq = _gaq || [];
_gaq.push(['_setAccount', _anId]);
alert('You needed this: ' + _somethingElseNeededInJsFile);
Related
I know how to insert a standard script to the body or header (changing .body or .header) depending on the case with:
document.body.appendChild(document.createElement('script')).src = 'https://url.com';
But I have a script that I need to insert into the header but it contains a var and I’m not sure how I should insert it.
<script type="text/javascript"> var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; </script> <script type="text/javascript" src="//cdn.iubenda.com/cs/iubenda_cs.js" charset="UTF-8" async></script>
Any ideas?
You can create a script element and add the content with .innerHTML, afer just insert to body (or header).
var script = document.createElement('script');
script.innerHTML = ` var _iub = _iub || []; _iub.csConfiguration = {"countryDetection":true,"reloadOnConsent":true,"consentOnContinuedBrowsing":false,"perPurposeConsent":true,"purposes":"1,2,3,4,5","lang":"en","siteId":xxxx,"cookiePolicyId":494xxxx,"cookiePolicyUrl":"https://www.iubenda.com/privacy-policy/xxxx", "banner":{ "acceptButtonDisplay":true,"customizeButtonDisplay":true,"rejectButtonDisplay":true,"position":"float-bottom-center","backgroundOverlay":true }}; `;
document.body.appendChild(script);
I need to place an entire javascript function in a div and show it for testing purposes, how can I accomplish this? I am doing this from code behind in asp.net
EDIT
<!-- Facebook Conversion Code for Website Purchase -->
<script type='text/javascript'>
(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
})();
window._fbq = window._fbq || [];
</script>
Edit: You need to do some trickery: How to show <div> tag literally in <code>/<pre> tag? Which says that you need to escape your < and > characters in your tag to < and > for them to show in the <pre>. The example below has been modified to show this.
You should try using the html <pre> tag, it's commonly supported and does exactly what you're asking for:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
<pre>
<script type="text/javascript">
console.log('hi');
</script>
</pre>
should show something like
<script type="text/javascript">
console.log('hi');
</script>
I want to give users a snippet to put on their own sites which loads a generic javascript file with a unique ID for that user. This is so the content which loads up is dependant on which user id is associated with it.
My best guess so far is something like this:
<script type="text/javascript">
var UID = '';
(function() {
var url = www.test.com/embed.js';
})();
</script>
<noscript>Please enable JavaScript to view this content</noscript>
content powered by <span class="logo">Test</span>
I havent had a lot of luck with this code. Can anyone explain how I should be approaching this please?
Here is the way that google does it. Let me know if you need help applying it:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
Ref. https://developers.google.com/analytics/devguides/collection/gajs/
You need to append <script> tag to the DOM.
You should put your entire script inside a single scope (function)
(function(window, uid) {
var document = window.document;
// create your <script> element
var e = document.createElement("script");
e.src = "//my.website.com/my-script.js?user-id=" + window.encodeURIComponent(uid);
// insert it before the very first <script> element already in DOM
var s = document.body.getElementsByTagName("script")[0];
s.parentNode.insertBefore(e, s);
})(window, "some-user-id");
I have some script tag like this:
<script src="cordova-2.5.0.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
<script src="js/jquery.xdomainajax.js"></script>
<script src="js/xml2json.js"></script>
<script src="js/ZipPlugin.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
<script src="js/prefixfree.min.js"></script>
This is my app i wrote using phonegap for android but i want to use code in web. And i dont use all for web page.
Have any way to do it like using if else like this in html:
if(anything) {
<script src="cordova-2.5.0.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
<script src="js/jquery.xdomainajax.js"></script>
<script src="js/xml2json.js"></script>
<script src="js/prefixfree.min.js"></script>
} else {
<script src="js/ZipPlugin.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
}
I am a dumper, please help me.
Thanks for reading!!!
Edit:
if i want to change my script tag:
<script src="js/prefixfree.min.js"></script>
Become like this:
<script src="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/js/prefixfree.min.js"></script>
Have anyway to make a variable like:
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/"
And then use in tag like this:
<script src = "key + 'js/prefixfree.min.js'"></script>
How about this,
function registerScript(scriptPath) {
var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
scriptTag.src = scriptPath;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
}
if (anything) {
registerScript("cordova-2.5.0.js");
}
For the first part. you can do this:
if (anything) {
$('head').append('<script src="cordova-2.5.0.js"></script>')
.append('<script src="js/jquery-1.7.2.min.js"></script>')
.append('<script src="js/jquery.mobile-1.1.1.min.js"></script>')
.append('<script src="js/jquery.xdomainajax.js"></script>')
.append('<script src="js/xml2json.js"></script>')
.append('<script src="js/prefixfree.min.js"></script>')
} else {
$('head').append('<script src="js/ZipPlugin.js"></script>')
.append('<script src="js/jquery-ui.min.js"></script>')
.append('<script src="js/jquery.ui.touch-punch.min.js"></script>')
}
To change the script tag, do this:
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/"
$('script[src="js/prefixfree.min.js"]').attr('src', key + 'js/prefixfree.min.js');
Using jquery template :
DEMO : http://jsfiddle.net/abdennour/R36Qc/3/
Your template :
<script id="myscripts" type="text/x-jquery-tmpl">
<script src="${myurl}" type="text/javascript">
{{html "</sc"+"ript>"}}
</script>
Your javascript code :
$('#myscripts').tmpl(myarray).prependTo('head')
The branching (if) is done on array of String (src of js) :
var myarray=[]
if (anything) {
myarray=[{myurl:"cordova-2.5.0.js"},
{myurl:"js/jquery-1.7.2.min.js"},
{myurl:"js/jquery.mobile-1.1.1.min.js"},
{myurl:"js/jquery.xdomainajax.js"},
{myurl:"js/xml2json.js"},
{myurl:"js/prefixfree.min.js"},
{myurl:"js/jquery.mobile-1.1.1.min.js"}
]
} else {
myarray=[{myurl:"js/ZipPlugin.js"},
{myurl:"js/jquery-ui.min.js"},
{myurl:"js/jquery.ui.touch-punch.min.js"} ]
}
See : https://stackoverflow.com/a/5462679/747579
To check result , open browser inspector :
You could make a script to create all the scripts node like:
<script>
var head= document.getElementsByTagName('head')[0];
var key = '';
if(anything) key = 'http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/';
var scripts = new Array()
scripts[0] = 'js/prefixfree.min.js';
scripts[1] = 'js/foo.js';
for(var s in scripts) {
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= key + s;
head.appendChild(script);
}
</script>
You could use pure javascript like that:
<script>
var key ="http://smartphone.thnt.vn/VietGames/GhepTranhTu/Web/",
file=document.createElement('script');
file.type = "text/javascript";
file.src = key + 'js/prefixfree.min.js';
document.getElementsByTagName("head")[0].appendChild(file);
</script>
<script>
if(foo) {
document.write('<script src="a.js"><\/script>');
} else {
document.write('<script src="b.js"><\/script>');
}
</script>
In this case document.write is a valid option. The script tags are blocking anyway.
You can include script files dynamically using JavaScript. See an example here:
Load jQuery with Javascript and use jQuery
Here is my GATC. It is located in the FOOTER of my application.
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXX-XX']);
_gaq.push(['_setDomainName', 'mysite.com']);
_gaq.push(['_addIgnoredRef', 'mysite.com']);
_gaq.push(['_setCustomVar',1,'UserType','Visitor', 2]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
If I want to set some new custom variables in the BODY page, how would I do that?
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setCustomVar',2,'NewVar','Name', 2]);
</script>
Or
<script type="text/javascript">
_gaq.push(['_setCustomVar',2,'NewVar','Name', 2]);
</script>
To summarize:
I need to define some custom variables in the body of a page and my GATC is in the footer. I'm not quite sure the meaning of _gaq = _gaq and how it will effect this. Should it be in the snippet to define the custom variable in the body and then again in the GATC in the footer?
var _gaq = _gaq || [];
This line uses existing _gaq array or creates a new one and assigns to _gaq if it hasn't been defined(or contains falsy value). Therefore your first option (containing _gaq assignment) is better.