Inserting <script>codehere</script> in header via JS in the body? - javascript

http://jsfiddle.net/8wGRg/
<script>
document.getElementsByTagName("head")[0].appendChild("<scr" + "ipt>alert('Hi!');</scr" + "ipt>");
</script>
I have a PHP string which contains JS code. For the sake of this code, lets say my string is <script>alert('Hi!');</script>. Within the body of my HTML document, how can I use JS to insert the JS string into the head.
As you can see, I'm breaking the word script into two parts so that it doesn't actually process it in the body before pushing it to the head.
The PHP string contains this:
<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>
<script type='text/javascript'>
googletag.cmd.push(function() {
googletag.defineSlot('/1019006/ba_ad_footer_728x90', [728, 90], 'div-gpt-ad-1378123123651-0').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
PHP code to generate JS:
<?php $header_code = $GLOBALS['settings']['header_code']; // just an example of how I load the code ?>
JS to insert the PHP
document.getElementsByTagName("head")[0].appendChild("<?php echo $header_code; ?>");

It doesn't append it because you are trying to append a string instead of a DOM node.
var s = document.createElement('script');
s.appendChild(document.createTextNode('alert("Hi!")'));
document.getElementsByTagName("head")[0].appendChild(s);

Related

Write JavaScript code inside JavaScript and all in PHP?

I have an ad that will appear when certain conditions, and when that ad appears, the ad will detect the width of the screen and use the ad size that I specify.
I did this using JavaScript, and inside JavaScript and all are in PHP. Problems arise when writing in document.write.
Could you please help me solve this problem.
This is my code:
<?php
if(!empty($variable1)) {
echo '
<script type="text/javascript">
var swidth = screen.width;
if (swidth >= 1218) {
document.write('
<script type="text/javascript">
document.write("
<script type='text/javascript'>
var adcode = {abcdefg};
</script>
<script type='text/javascript' src='http://domainname.com/ads.js'></script>
");
</script>
');
}
</script>
';
} else {
if(!empty($variable2)) {
echo $ads2;
} else {}
}
?>
from line 13 to 22 replace:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://domainname.com/ads.js';
$("body").append(script);
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = 'sc.js';// or url to the script file;
$("body").append(script2);
and sc.js:
var adcode = {abcdefg};
BUT
The best way to add JS in PHP:
<?php
// ...
?>
<script src="url_to_script"></script>
<?php
// ...
?>
Manipulations with DOM elements must be defined in JS and not affect PHP.

removing the need for {ldelim} and {rdelim} in JavaScript within Smarty 2 templates

I have the following block of JavaScript in a Smarty 2 template file.
The code is verbatim to what has been provided to me from the provider, but it quite noticable that I have had to add in a number of {ldelim} and {rdelim} Smarty tags in to replace the JavaScript { and }.
I need to feed in the $log_id, that won't change, however is there a way for me to write this cleaner without the need for all these tags making the code look less readable?
I am aware of the {literal} tag, but opening and closing that tag would arguably make it less readable.
<script type='text/javascript'>
window.Muscula = {ldelim} settings:{ldelim}
logId:"{$log_id}", suppressErrors: false, branding: 'none'
{rdelim}};
(function () {ldelim}
var m = document.createElement('script'); m.type = 'text/javascript'; m.async = true;
m.src = (window.location.protocol == 'https:' ? 'https:' : 'http:') +
'//musculahq.appspot.com/Muscula.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(m, s);
window.Muscula.run=function(c){ldelim}eval(c);window.Muscula.run=function(){ldelim}{rdelim};{rdelim};
window.Muscula.errors=[];window.onerror=function(){ldelim}window.Muscula.errors.push(arguments);
return window.Muscula.settings.suppressErrors===undefined;{rdelim}
{rdelim})();
</script>
In that case, you may change smarty delimiter
http://www.smarty.net/docsv2/en/language.escaping.tpl
<?php
$smarty->left_delimiter = '{{';
$smarty->right_delimiter = '}}';
$smarty->assign('log_id', 'something');
?>
Your template would them become:
(note the double brackets for variables {{$variable}} )
<script type='text/javascript'>
window.Muscula = { settings:{
logId:"{{$log_id}}", suppressErrors: false, branding: 'none'
} };
(function () {
var m = document.createElement('script'); m.type = 'text/javascript'; m.async = true;
m.src = (window.location.protocol == 'https:' ? 'https:' : 'http:') +
'//musculahq.appspot.com/Muscula.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(m, s);
window.Muscula.run=function(c){eval(c);window.Muscula.run=function(){};};
window.Muscula.errors=[];window.onerror=function(){window.Muscula.errors.push(arguments);
return window.Muscula.settings.suppressErrors===undefined;}
})();
</script>

Injecting javascript dynamically and using it

I also create a javascript file dynamically that uses those variables:
function callbackF(data){
console.log(data.script);
document.getElementsByTagName('head')[0].innerHTML=data.script;
var script = document.createElement("script");
script.setAttribute("src", "http://widget.example.com/sprk.1.0.2.js");
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "grazit_script");
document.getElementsByTagName('head')[0].appendChild(script);
}
This is what i get in my head:
This is what is printed to the console log:
<script type='text/javascript'>var dbnwid=16476; var dbnpid=23369; var dbnwebid=19720; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>
and then the script:
<script src="http://widget.example.com/sprk.1.0.2.js" type="text/javascript" id="grazit_script"></script>
The second script should get the variables that are in the second script..but it doesnt..then it complains about why it doesnt get those variables
UPDATE:
Both of those ways below didnt work for me:
eval(data.script);
var ss= new Function(data.script)();
Because scripts run when they are loaded. Adding a script tag using innerHTML doesn't run the code inside the tag.

javascript and jquery override

I am making a small project that will let:
different websites to load my external javascript file: something like this:
<script type="text/javascript">
var vsid = "SA89696";
(function() {
var vsjs = document.createElement('script'); vsjs.type = 'text/javascript'; vsjs.async = true; vsjs.setAttribute('defer', 'defer');
vsjs.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'example.com/robot/robot.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(vsjs, s);
})();
</script>
now I want to use jquery in my javascript file, I dont have problem to load it by myself,
but I dont want to cause errors to the curresnt website if it already loaded jquery.
do you have any suggestions how to load jquery with no overrides.
You need something like this:
<script>
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "path/to/jQuery";
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>
It checks if jQuery is loaded or no..
Source

Is there a way to combine loading jQuery and Google Analytics?

I currently have the following:
<script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script>
<script>
//<![CDATA[
google.load('jquery', '1.6');
//]]>
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '...']);
_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>
Seems like two very different ways to load js. Is there some way I can combine these so the load is most efficient?
For this call you need to load google jsapi first.
google.load('jquery', '1.6');
If you just want the jquery loaded asyncronously parallel to other script file calls, use the following :
var jq = document.createElement(“script”);
jq.src = “/path/to/jquery.js”; jq.type=”text/javascript”; jq.async=true;
document.getElementsByTagName(“head”)[0].appendChild(jq);

Categories

Resources