Assigning the value of "<script src=" directly to another element - javascript

Is it possible to assign a value of <script src="http://domain.com/external.php"></script> directly to another variable, like the following (not using JQuery, but simple Javascript):
<script>
document.getElementById('ID').innerHTML=<script src="http://domain.com/external.php"></script>;
</script>

maybe doing something like this is better
script=document.createElement('script');
script.src='http://whatever.js';
document.getElementsByTagName('head')[0].appendChild(script);

If you're trying to append the script inside the DOM as a string, you have to do something like this :
var script = '<script src="http://domain.com/external.php"></scr'+'ipt>';
document.getElementById('ID').innerHTML = script;
the closing script tag will cause issues in parsing when inserted as a string because it closes the current script, concatenation will solve that.

Related

Programatically escape / script closing tag in javascript

I have this variable which contains a script html code
<script>
var script = "<script>console.log('script here')</script>"
</script>
how do we programmatically escape the / in the closing tag </script> so it will look like the code below
<script>
var script = "<script>console.log('script here')<\/script>"
</script>
It does not work as you think.
The first fragment of code does not work because the browser finds the </script> piece in the string and thinks that it is the closing tag of the script element. It treats the rest of the script and the real </script> closing tag as regular text and displays it in the page (except for the </script> tag).
This means that only a fragment of your script is parsed, the parser finds a syntax error in it (the string is not closed) and the script does not run.
There is no way to fix this using JavaScript code. It is not a coding problem. It is an HTML problem (kind of) and its only solution is to write the HTML in a way that avoids the issue.
The HTML document contains a closing tag </script> inside the body of a script element. For normal HTML content (a paragraph, for example) the solution is straight forward: use < and > to encode < and >:
<p> This is a paragraph that contains a <p> closing tag</p>
You should do it anyway everywhere you want < and > to represent themselves (to be rendered and not interpreted as tag markers) to produce correct HTML.
This simple solution is not possible in the <script> element because the content of the <script> element is not parsed by the HTML parser. It only finds the first appearance of the </script> closing tag and passes the content to the JavaScript parser. And the JavaScript parser does not understand < and >.
However, there is a simple solution for your problem. Make sure that the script does not contain the string </script> and everything will work without problems.
Usually, this is done either by writing:
var script = "<script>console.log('script here')<\/script>"
or by splitting the string in two sub-strings in the middle of the script word:
var script = "<script>console.log('script here')</scr" + "ipt>"
The first solution looks a little better.
Another, even easier, solution is to not put the JavaScript code into an inline script element but keep it in a .js file and link that file into the HTML document:
<script src="my-fancy-script.js"></script>
The file my-fancy-script.js looks like this:
var script = "<script>console.log('script here')</script>"
This way, the content of the my-fancy-script.js file is passed directly to the JavaScript parser that is not fooled by any appearance of </script> in the code.
An approach could be:
var script = "<script>console.log('script here')</script>";
script = script.replace('</script>', '<\/script>');
The same for the opposite:
var script = "<script>console.log('script here')<\/script>";
script = script.replace('<\/script>', '</script>');

convert blocks from text/plain to text/javascript and execute it

my problem is as follow.
I have a multiple script blocks that contain javascript code type of text/plain.
So my question is is there any script that i can dynamically convert them from text/plain to text/javascript type and execute its content ? The problem i'm having is the place of execution, because scripts contain document.write so the output is appended in the end of the html not on the location of the script itself.
eg: let's say something like this
<script type="text/plain">alert('hello world');</script>
<script type="text/javascript">
$(document).ready(function(){
$("script[type*=plain]").each(function() {
$(this).attr('type','text/javascript');
});
});
</script>
thnx
Modifying a script element in place doesn't cause it to be executed. You need to create a new script element with the appropriate content. Another option is to eval() the contents of the old element:
$(document).ready(function(){
$("script[type*=plain]").each(function() {
eval($(this).text());
});
});
You can go with some nasty approach, of selecting the tag with type=plain and then accessing its innerText attribute, assigning it to eval method.
var el = $("script[type*=plain]")[0];
eval(el.innerText);
But I'd try to avoid using eval
If there's a different approach I'm not aware of it, and for this I am sorry.
You can not make document.write to place it's output in place of <script> element if you change script's type, because entire page's javascript code woudn't re-run every time you add new <script> or evaluating existing one.
If you want to replace <script type="text/plain"> with the result of script execution, you can return some string from that script instead of using document.write and then insert this string in place of <script type="text/plain"> element:
<script type="text/plain">
var result = "line1<br>";
result += "line2";
alert('hello world');
result
</script>
<script type="text/javascript">
$(document).ready(function(){
$("script[type*=plain]").each(function() {
$(this).replaceWith(eval($(this).text()));
});
});
</script>

Javascript in html syntax in link

I am having a problem adding a js variable inside a html link where I believe I have the syntax wrong as it's not adding the content of the variable to the link string.
Here is what I'm trying:
href="http://www.facebook.com/sharer.php?u='+url+'">
Where I'm I going wrong here?
That is not possible to do :).
You have to do it javascript all the way, like:
href="javascript: document.location='http://www.facebook.com/sharer.php?u=' + url;"
You are trying to treat HTML as if it were JavaScript. You can't just jump in and out of the two languages.
If you want to modify an existing link, you need to use DOM Manipulation. This is covered as part of the introduction to JavaScript hosted by the W3C.
You can't do that. You will need to use javascript like this:
... within <head> tag ...
<script type="text/javascript">
window.onload = function() {
document.getElementById('myLink').href = "http://www.facebook.com/sharer.php?u="+url;
}
</script>
... within <body> tag ...
<a id="myLink" />
You need to be outside of the string in order to concatinate your URL.
In this case your string is created using a double quotation mark however you're trying to break out of the string by using a single quotation mark.
I'm assuming here that html is a Javascript variable, which it might not be:
var href = "http://www.facebook.com/sharer.php?u=" + url + ">";
I do not think you can just add a javascript variable inside an href like that. Try this:
Foo
document.ready(function(){
var url = "yahoo.com" ;
$("#linkid").setAttribute("href",url) ;
}) ;
When the browser loads all the elements, document.ready executes the method to set the href attribute of your anchor tag.
So you have an anchor tag like so:
<a id="linkid"/>
$("#linkid") gets the anchor tag element, while setAttribute("href", url) will set the link to your href attribute.
Hope it makes sense.

Insert JavaScript code from JavaScript

i need gets a html code by jsonp like method, and display this on a div element. This works with simple html like an images, text, etc. But now the code can content a JavaScript tags and need insert this on a div, but the javascript, don't runs, i resume it with a example:
var div = document.getElementById('mydiv');
div.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';
this don't works, too i probe:
var otherdiv = document.createElement('div');
otherdiv.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';
div.appendChild(otherdiv);
But don't works too.
How I can insert the code in away that the JavaScript runs?
The most straightforward way is to extract all JavaScript and eval it.
You can extract JavaScript with a regular expressions like:
var match = html.match(new RegExp("<script[^>]*>(.+)</script>"));
console.log(match);
This is a far from optimal way of executing JavaScript, very error prone and possibly unsafe. I would strongly advise against it.
You should use a script loader like LAB, yep/nope, or Frame.js. The browser has built-in restrictions, script loading is the best practice for including scripts on a page.
You also would have to escape the single quotes.
console.log(\'I run!\');

How to store javascript code without it executing?

I'm trying to have adsense javascript code added to a designated div location using jquery but it seems javascript code does not sit well inside a jquery variable. It executes. I've tried using php's htmlentities to encode it for storage, but I can't get it to decode naturally. What should I do? Do I need a javascript based replacement for htmlentities_decode?
This is how far I've gotten, and .html() is not automatically decoding the htmlentities encoded html.
var html_1 = "<?php echo htmlentities('<script>adsense ad code here</script>'); ?>";
if (html_1)
{
jQuery('#id_wpt_adblock_1').html(html_1);
}
It seems like you could just put the javascript code in its own function, then just execute that function whenever you need it. That sounds so obvious that you must have eliminated that option already, but why?
<script> tags are automatically executed when they are added to the DOM. So, when the string is added via html(), the <script> is added to the DOM, and than ran.
The issue here, is the <script> tags in the string. When the browser sees 'em, it may try to run the script. Try to change the string to this:
var html_1 = "<?php echo '<scr"+"ipt>adsense ad code here</scr"+"ipt>'; ?>";
This should output:
var html_1 = "<scr"+"ipt>adsense ad code here</scr"+"ipt>";
Which should work.
EDIT: You said this string is in a variable, try using str_replace to replace the tags.
var html_1 = "<?php echo str_replace(array('<script>','</script>'), array('<scr"+"ipt>', '</scr"+"ipt>'), $_SESSION['wpt_ad_content_1']); ?>";
document.write('<script src="your_script.js"><\/script>')</script>

Categories

Resources