Jquery append if location finish with W12345 - javascript

I need to do a conditional append here is the example url
www.google.com/default.asp/W12345
I want to append a JS file if the url has W and a random string of numbers after it.
How can i achieve this?

Try something like this:
<script>
if (/default\.asp\/W[\d\w]*$/.test(location.href)) {
document.write("<script src='/path/to/your/js/file.js'>");
}
</script>
Insert that code anywhere on the page, typically either in the head, either at the very end of the document.

Use the below snippet on dom-loaded. Here I'm making use of regular expression if it ends with url /wSomeString or /WsomeOtherString.
if(/.+\/w.+$/i.test(window.location.href)) {
var scriptDom = document.createElement("script");
scriptDom.type = "application/javascript";
scriptDom.src = "url/to/js"; //update JS url here.
document.body.appendChild(scriptDom);
}

Related

Set Script Source from the same file instead of a different one?

I create an iframe in a file and insert a <script> tag as its content. The Script src is loaded from a different file called test.js. Here is how it is done:
var scriptElement = document.querySelector("#your-widget");
var iframe = document.createElement("iframe");
scriptElement.parentNode.insertBefore(iframe, scriptElement.nextSibling);
var script = document.createElement("script");
iframe.contentWindow.document.appendChild(script);
script.src = "http://www.example.com/test.js";
Instead of loading the content of the script from http://www.example.com/test.js I want to take it from the same file where the above code is. This would like this:
var scriptElement = document.querySelector("#your-widget");
var iframe = document.createElement("iframe");
scriptElement.parentNode.insertBefore(iframe, scriptElement.nextSibling);
var script = document.createElement("script");
iframe.contentWindow.document.appendChild(script);
script.src = // ????
// the following JavaScript code should be placed inside the script
function mywidget() {
// some code
return true;
}
mywidget.succeeded = mywidget();
How can I set the Script Source from the same file instead of a different one?
If you literally just want to place that exact snippet in a script tag, you can just do so using .innerText.
script.innerText = 'function mywidget() { ...';
Then it will execute as is when it's inserted into the DOM. If you want to dynamically find and inject that code, read on.
There are exactly two ways to load a script on a page.
Add a <script> with the src attribute pointing to a file.
Create a <script> tag then set the contents to whatever you want to execute.
var script = document.createElement('script');
script.innerText = 'console.log("Hello, World!")';
document.body.appendChild(script);
If you want to extract part of a script and use those contents then the best you can do is load the contents via ajax and inject it using method 2.
Assuming you have jQuery (for easy AJAX work):
$.ajax({
url: 'path/to/script.js',
dataType: 'text', // make sure it doesn't get eval'd
success: function(contentsOfScript) {
// Refer to method 2
}
});
Now you can go about extracting the contents of that snippet in one of two ways:
Know exactly which line it begins on.
var lines = contentsOfScript.split('\n');
var snippet = lines.slice(lineNumber + 1); // adjust for 0 indexing
Generate a regular expression to identify where your code begins. This is rather tricky and very error prone if your snippet isn't easily distinguished from other code.
var snippet = contentsOfScript.match(/function mywidget.+/)[0];
Neither of these methods will work if you perform any minification on your code.

Append <script> when preparing a html code for iframe: without executing

I am preparing an HTML code on memory for an Iframe, when I use append it executes the code.
html = $(parser.parseFromString($("#EHtml").val(), "text/html"));
js = '<script>' + $("#EJs").val() + '</script>';
html.find('body').append(js);
$("#EHtml").val() contains HTML code
and the append function does its job but also executes the code.
Any thoughts here?
You need to just store a reference to the string of code and do 1 of two things: either do the append interaction only when you want to run the code later, or run eval(jsString) when you want to run it.
Script tags won't execute if their [type] attribute is set to anything wacky.
<script type="wacky/non-executing">
console.log("This will not execute! You will not see this!");
</script>
Its Obvious to run script when you insert it, between script tags,Because your DOM already complete loads.
And it will run twice because you put it inside the body So when you body content canges the script ran again!
So you have to set your Script tag on head of an iframe to it will run Only when you insert it or reload,and not again an again !
I am not suggesting you to use eval() because it is dangerous to use for script evaluation,eval() is basically used for another purpose !
Use <script></script> tags to run your script and place it on head if you don't want to ran it twice .
var script = document.createElement('script');
script.innerHTML = $("#EJs").val();
iframe.contentWindow.document.head.appendChild(script);
May be this will help you..
Try using entities, like
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
html.find('body').append(encodeHtmlEntity(js));
to append and
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
decodeHtmlEntity(html.find('body').val());
to read.
Got it in the way I need.
I was trying to add the script tag without using ways around the problem - I mean I just wanted to add the tag as it is. Thanks every body for the inputs - I got the solution from your advises...
in the end I could append to the Iframe but it was executing in the main page context. What was causing the problem was using JQuery to do the appending... so here it is:
frame = document.getElementById("frame");
out = (frame.contentWindow) ? frame.contentWindow : (frame.contentDocument.document) ? frame.contentDocument.document : frame.contentDocument;
out.document.open();
out.document.write(html.find('html')[0].outerHTML);//HTML added here
//JS appended here
js=out.document.createElement('script');
js.innerHTML = 'js code here';
out.document.getElementsByTagName("body")[0].appendChild(js);
out.document.close();
I hope its useful for someone...

Phantomjs/Casperjs get url from JS script inside page

I'm building a scraper with phantom/casper.
At this point, I need to extract a URL that appears in the page only inside a js script.
Example of the page source code :
<script>
queueRequest('URL.aspx?var1='+VAR1+'&var2='+VAR2, getPageMenu');
</script>
I have no problem evaluating VAR1 and VAR2, as they are in the page context, but I need URL, which is hardcoded and has no reference to it. URL is of course different according to the page I'm on and I have no way of guessing it. Any ideas?
My ideas :
As the URL is called on page load to fill a div wih AJAX, I was thinking of maybe capturing the XHR request, but I don't know how.
I managed to get the script elem I need, using document.getElementsByTagName('script'). That may be one way to go, but how do I get only the line I need out of 200+ lines? (the one starting with queueRequest)
SO to make my question clear :
Which idea is better, 1 or 2?
if 1 : How do I capture the request URL with casper?
if 2 : How do I get the right line in my script?
If you want to search your script blocks, you can try something like this:
found = null;
scripts = document.getElementsByTagName('script');
for (i = 0; i < scripts.length; i++)
{
matches = /queueRequest\('(.+)\?/.exec(scripts[i].innerText)
if (matches)
{
found = matches[1];
break;
}
}
alert(found);
There might be tighter ways to implement the same thing but the regex is roughly what you're after. Note that this will only get you the URL part of the first appearance of queueRequest('something.something?...) in embedded script blocks.

$_GET inside javascript file?

For example, I have an script like this: <script src="myjs.js?lol=asd"></script>.
Is there anyway to get the lol inside the js file to alert it, for example, like we can do in PHP? Like:
var lol = $_GET['lol'];
alert(lol);
Use the code from How may I reference the script tag that loaded the currently-executing script? to get a reference to the script tag:
var scripts = document.getElementsByTagName('script');
var thisScriptTag = scripts[scripts.length - 1];
Then you can use thisScriptTag.src to access its src attribute and parse it to get the variable you are looking for
You can't do this with javascript.

How to append <script> that will be executed?

Tried this :
Click me
<div id="pasteContent"></div>
​
var elemFunc = '<script>alert("myString");</script>';
$("#showAlert").click(function () {
$("#pasteContent").html(elemFunc);
});
​
What I'd like to do is to append the string alert(myString); (which is a script) that must be executed... how can I do? Is it not correct?
Add a backslash before / in </script>: http://jsfiddle.net/kxALH/3/
Your code failed, because </script> is considered as a close tag for your fiddle script. As a result, your first fiddle looked somewhat weird.
Note: If you want to execute an arbitrary string of code, $.globalEval('alert("myString")'); may suit better.
try it whit a jquery script object like this
var elemFunc = $('<script>')
.attr('type', 'text/javascript')
.html('alert("myString");');
$("#showAlert").click(function () {
$("#pasteContent").append(elemFunc);
});
Try this:
var elemFunc = '<script>alert("myString");</' + 'script>';
If you have your JS inside your HTML
Try this:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);
Note that the script will load and you can access the variables inside it, but you wouldn't see the actual tag in the DOM.
Since what you're going equates to an eval, and eval IS evil, You can use an external script and $.getScript(), to load it via ajax...
$.getScript("http://scriptURL.com/script.js", function(){ init(); });

Categories

Resources