Injecting and executing JavaScript string in a specific HTML element - javascript

I have received the latest Disqus comments string (JavaScript code) from the server using ajax call that has document.write code in it.
I want the page to execute this code inside a specific DIV (by it Id, which is '#recent-comments') in the page, how do I do that?
I use jQuery 2.1.1.

Its a bit nasty but you could eval it inside a closure function:
var message =" document.write('hello'); ";
eval("(function(){"+
"var document = {write:function(text){$('#divName').html(text)}}; " +
message +
" })();");
JSFiddle DEMO (I've had to change write to wrie otherwise jsfiddle disallows it, just need to change back for your case)

Since it is coming as a string, you need to create a script element and put the string (inside document.write) as a element to the div.
var sampleStr = "document.write(\"Hello World\");";
var str, scriptElement = document.createElement('script');
str = sampleStr.replace(/["']/g, '"');
str = str.replace(/"document.write/g, "");
scriptElement.innerHTML = str;
$('#div1').append(scriptElement);
Updated Fiddle

Related

Remove tag and content using Javascript

What I want is to get the content of a specific #id, remove a few tags and its contents, add some html before and after it, and then set that finished content as the body content.
I now have the following code, containing a mixture of Javascript and jQuery, although obviously not the right one - resulting in a [object Object]-message.
My code looks like this:
var printContents = jQuery("#"+id).clone();
var printContentsBefore = '<html><head></head><body><table><tr>';
var printContentsAfter = '</tr></table></body></html>';
var mainContents = printContents.find(".td_print").remove();
document.body.innerHTML = printContentsBefore + mainContents + printContentsAfter;
Any ideas of how to make this work?
Your code does not convert the cloned jquery object to a string. Modify your code as follows:
document.body.innerHTML = printContentsBefore + mainContents.html() + printContentsAfter;
Beware that the .html method output will not include the html representation of the container element itself (ie. of the #id clone in your case).

Why am I getting an error when trying to add the src attribute to an img tag using JavaScript within Colfusion?

I am using ColdFusion to connect to and execute methods from a Web Service. I store the contents of the returned xml string in to a ColdFusion array then I convert the ColdFusion array into a JavaScript array, so that I may populate the content of my HTML document.
My problem arises when trying to add a photo to a unordered list called "agent_photo_list". Specifically when I call the .setAttribute method. It seems to involve the 'src' parameter. The JavaScript code works as I expect when it is not inside the cfscript tag and WriteOutput method. I have researched the problem, I haven't been able to find a reference that is sufficiently similar. I am still having trouble understanding what my problem is. I have included my code below:
cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute('src', "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
')
</cfscript>
I am using a jpg file located in my _images folder for testing purposes, I will later change it to agent.photourl.
The error I get is provided below:
Invalid CFML construct found on line 117 at column 35.ColdFusion was
looking at the following text:<p>src</p><p>The CFML
compiler was processing:<ul><li>An expression beginning
with WriteOutput, on line 111, column 17.This message is usually
caused by a problem in the expressions structure.<li>A script
statement beginning with WriteOutput on line 111, column
17.<li>A cfscript tag beginning on line 102, column 10.</ul> The specific sequence of files included or processed is: C:\inetpub\wwwroot\webservice.cfm, line: 117
I am curious to why my JavaScript is functional inside the cfscript tag until calling the setAttribute method and why it is functional outside the cfscript tag.
I will appreciate your insight. Thank you.
You need to wrap the src in "". Also, add the ";" at the end of WriteOutput closure. The below code should work for you.
<cfscript>
WriteOutput('
<script language = "JavaScript">
var #ToScript(array, "jsArray")#
var agent = jsArray[0];
document.getElementById("output").innerHTML = agent.firstname + " " + agent.lastname;
var imgurl = "_images/agentphoto.jpg";
var node = document.createElement("LI");
var imgnode = (document.createElement("IMG"));
imgnode.setAttribute("src", "imgurl");
node.appendChild(imgnode);
document.getElementById("agent_photo_list").appendChild(node);
</script>
');
</cfscript>

Parse HTML string containing script tag and document.write

I have below string. It has nested document.write string statements. I want to add text contents of innermost script to document.
"document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')"
How can I parse this string so that Hello World gets added in document. For e.g. html output can be as below.(can be in body or div, anything is ok.)
<body>Hello World</body>
P.S. there can be any number of nested document.write statements. Need to parse this string which can handle n level of nesting.
Well I figured it out now.
var str = "document.write('<script>document.write(\"<script>document.write(\"Hello World\");<\/script>\");<\/script>')";
var aStr, scriptEle = document.createElement('script');
aStr = str.replace(/["']/g, '"');
aStr = aStr.replace(/"<script>document.write/g, "");
aStr = aStr.replace(/;<\/script\>"/g, "");
scriptEle.innerHTML = aStr;
// console.log(aStr);
document.body.appendChild(scriptEle);
This also handles n level of nesting.
You will basically have to tell the script to execute the script inside the <script> tags.
You can achieve this by doing this
var code = "<script>document.write(\"Hello World\");</scr"+"ipt>";
$('body').append($(code)[0]);
Which will happily display hello world in the body tags. You can use this approach to get your script executed by appending it on any tag. Here is the jsfiddle and an SO answer that can give you an idea as to how to be able to execute a js which gets appended dynamically
Hope that helps :)

Get URL parameters with Javascript

Hi I have the following tag inside my HTML:
<script type="text/javascript" src="http://XX/teste1.php?BLABLABLA"></script>
Is there somewhay inside teste1.php, using JS to retrieve the parameters BLABLABLA? If I use window.location.href I get the index.php location (of course) but I need to get the parameters sent to the external resource using JS and not PHP.
I think I understood what you are after. Take a look the following fiddle.
http://jsfiddle.net/gK58u/2/
You can see I'm manually loading in jQuery, and then getting the src from the script declaration.
===================
HTML Add an id to your script declaration
<script id="jquerysrc" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js?key=test"></script>
Javascript
$(document).ready(function() {
var scriptsource = "";
scriptsource = $("#jquerysrc").attr("src");
alert(scriptsource);
});
This will allow you see the url that your external js file is coming from. This is more a point in the right direction.
You can try this, without using jQuery.
var scripts = document.getElementsByTagName('script'),i,src;
for(i=0;i<scripts.length;i++){
src = scripts[i].src;
if (src && src.indexOf('?')>=0){
console.log(src.substring(src.indexOf('?')+1));
}
}
Currently JavaScript don't have any of the built-in function for such purpose. What you're talking about i.e. BLABLABLA is known as Query String. Which is attacked to the URL to make a dynamic web page (change the content depending on the condition)
First Method
Is to get the whole URL, and then replacing the URL with empty string and so on to get only the last element.
Second method
Another answer was posted with a function (custom function, not a builtIn function). In which you pass on a parameter to the method, which gets the parameter values for you. It is easy to understand too.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
To call the function, you use getParameterByName('prodId'). Use it inside a function or variable and you're good to go.
It seem you don't understand how PHP and JS works together.
Php generate HTML (maybe JS and CSS too). Then when this html is loaded by a client, JS is executed.
To get it in PHP or JS, you can use regex or modify the url from ?BLABLABLA to ?key=BLABLABLA. In PHP, "BLABLABLA" will be stored in $_GET['key']
EDIT :
well I misunderstood your question.
From "How to retrieve GET parameters from javascript?" :
-------------------------
With the window.location object. This code gives you GET without the question mark.
window.location.search.replace( "?", "" );
-------------------------
From your example it will return BLABLABLA
window.location DOC
EDIT2 :
When you generate your Javascript in teste.php, you should do this :
$str = "";
foreach ($_GET as $key => $value) {
$str = $key;
}
echo "var getParam = ".$str.";";
I don't see how to avoid foreach if you don't know what is given. You may have to rebuilt the parameters string ("?xxx=sss&ddd=zz...")
Now you JS variable getParam should contains BLABLABLA
Apolo

how to escape single quote in dynamically created HTML tag content

In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify() for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';

Categories