I have feedburner script which displays feeds, it looks like this:
<script src="http://feeds.feedburner.com/cnn/HIkg?format=sigpro" type="text/javascript" ></script>
I want to load this script which is on a different html page, so basically I'm loading html file with this script in it using:
$('#' + items[i]).load('content/' + items[i] + '.html');
This piece of code does load the html page but the script is not executed(working). How do I get the script to work once loaded?
According to the documentation :
Script Execution
When calling .load() using a URL without a suffixed
selector expression, the content is passed to .html() prior to scripts
being removed. This executes the script blocks before they are
discarded. If .load() is called with a selector expression appended to
the URL, however, the scripts are stripped out prior to the DOM being
updated, and thus are not executed.
If your url is just a plain url without a selector specified than the script should execute before it is removed.
Check the value of items[i] and check if it is a plain url without a selector or not.
If the url looks fine, you might be running into a cross-side scripting issue. The documentation also mentions:
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
If possible though I still would recommend for any script to be in an external file as that is good practice and doesn't clutter the html. Then you can use .getScript() as recommended by Raminson.
You can use the $.getScript() utility function:
Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript("/test.js")
Related
I have a Javascript library I'm working on. It can be self-hosted or run from another server. The script makes a number of AJAX calls and the preferred method is making POST requests to the same host as the including page. To allow for cross-domain calls it also supports JSONP, but this limits the amount of data that can be sent (~2K to safely accommodate most modern browsers' URL length limits).
Obviously the user including the script knows where they're getting it from and could manually select JSONP as needed, but in the interest of simplifying things, I'd like to detect, within the script itself, whether the script was loaded from the same host as the page including it or not.
I'm able to grab the script element with jQuery but doing a $('script').attr('src') is only returning a relative path (e.g. "/js/my-script.js" not "http://hostname.com/js/my-script.js") even when it's being loaded from a different host.
Is this possible and if so, how would I go about it?
Thanks in advance.
Don't use JSONP, use CORS headers.
But if you really want to do JS check, use var t = $('script')[0].outerHTML.
Effect on my page:
[20:43:34.865] "<script src="http://www.google-analytics.com/ga.js" async="" type="text/javascript"></script>"
Checking location.host should do the trick.
I am using a little javascript thingy (app?) from http://code.google.com/p/tumblrbadge/ to load my most recent tumblog post into my webpage. However, when I load the 'tumblr' section with AJAX using Jquery, the script does not get executed. I understand why this is and that I need to include the javascript file in the and execute it after the AJAX load is complete. My problem is this: I do not fully understand the tumblrbadge code and, when I include the script in the and call tumblrBadge() after loading, it does not run. How must I modify the tumblrbadge code to allow it to be run on demand from the ?
All of this is hosted at http://jquerytest.webs.com
It looks like your problem is that the script tags within the tumblr section of your site are not being executed. When you insert html into a page using ajax, you have to parse out the contents of any script tags and execute them separately.
After the content of the tumblr tab is inserted in your page, get all of its script tags with $("#contentOfTumblrTab script") and evaluate their innerHTML using eval().
Try $(window).onload instead of $(document).ready.
When an external JavaScript file is referenced,
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
is the JavaScript source (lines of code before interpretation) available from the DOM or window context in the current HTML page? I mean by using only standard JavaScript without any installed components or tools.
I know tools like Firebug trace into external source but it's installed on the platform and likely has special ability outside the context of the browser sandbox.
Nope. There's no Javascript API for loading the true content of <script> tags. This is actually not an oversight, but rather a security feature: suppose I request the .json file that Gmail requests via AJAX to load your inbox by putting it in an external <script> tag. A JSON document is valid Javascript (granted, without side-effects), so it would run without error. Then, if I could inspect the content of the external script, I would be able to read your e-mail. (I'm almost certain that Gmail is more complex than that, but most sites are not.)
So, making up a few things about how Gmail works, here's how the attack would look:
<script id="inbox" type="text/javascript" src="http://mail.google.com/OMGYOURINBOX.json"></script>
<script type="text/javascript">
// Supposing a value called `externalScriptContent` existed on a script tag:
var inboxJSON = document.getElementById('inbox').externalScriptContent;
var messages = JSON.parse(inboxJSON);
for(var i in messages) {
// Do something malicious with each e-mail message
alert(messages[i].body);
}
</script>
If a script tag had the value externalScriptContent, I could just put whatever URL in for the src that I wanted, and then summon up the remote file's contents, effectively circumventing AJAX cross-origin restrictions. That'd be bad. We allow cross-origin requests for remote scripts because they are run and run only. They cannot be read.
Firebug has these permissions because Firefox extensions have the ability to inspect anything that the browser requests; normal pages, thankfully, do not.
However! Bear in mind that, if the script is on your domain, instead of writing it in <script src="…"></script> form, you can pull it up with an AJAX request then eval it to have access to the contents and still only request it once :)
You can parse the <script> tag and re-request the js file by XMLHttpRequest, it will likely be readily served from cache and with credentials of the current page. But unless both your requesting script and the script in the tag originate from the same domain, the browser will disallow this.
In javascript, as a script loaded from somer host, is there any way to know what server/host I was loaded from? I need to make additional ajax requests back to that host and would prefer to figure out the host dynamically.
So if you include a javascript file on a page
<script src="http://somehost.com/js/test.js"></script>
when that javascript execute, within test.js ...
var host_loaded_from = ??? // should be somehost.com
Thanks
is there any way to know what server/host I was loaded from?
Yes, it's possible except when the script is loaded asynchronously using defer or async attributes since the last script in the DOM may not necessarily be the currently executing script in that case. See the comments by #kangax for more information.
Also, this same question was posted recently.
Inside your test.js, get the last script element which will be the currently being parsed script (test.js in your case), and get its src.
// test.js
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
One the src is found, parsed the host using regex.
src.match(new RegExp('https?://[^/]*'))
["http://somehost.com"] // for your example
Does the script know its own file name? ("test.js" in the OP question.)
If so, your script could query the dom for all script tags, looking for the ones with a src attribute. But you'd need to watch out for two scripts with the same file name loaded from different servers. Eg
<script src="http://somehost.com/js/test.js"></script>
<script src="http://somehost_number2.com/js/test.js"></script>
Here's JS that looks for all of the script tags in an el:
var scripts = el.getElementsByTagName('SCRIPT');
Nope, sorry.
If the <script> had an id, then maybe. But you can't really rely on that.
Not sure if that can be done with JavaScript. If the script is inside a PHP file do it like this:
...
var host_loaded_from = <?php echo $_SERVER[SERVER_NAME] ?>
...
On my site I include my JS scripts using PHP just for that reason. I'm interested to see if there's a better way.
Due to Same Origin Policy, you can make AJAX requests only to the origin (host + protocol + port), the HTML page (document) was loaded from - which is not necessarily the same as the origin your js was loaded from.
You can use window.location.hostname or document.location.hostname to find out the hostname of the document.
I'm loading some content into a jquery-ui dialog via .ajax. That's all working fine but now I've been given an OpenX ad to embed into the dialog & can't figure out how to do it. I know all the script is stripped when coming in via ajax, & I know how to use $.getScript to load .js files for use in the dialog, but the OpenX ad script I've got uses document.write so I think it's expecting to be embedded inline into the desired position on the page.
I've tried appending the escaped script string into the div on ajax success of the main content as below, but this results in the page being redirected to a page with just the ad on it.
Attempt shown below:
$("#" + idHelpPage).find(".adScript").append("<script type='text/javascript'>var m3_u = (location.protocol=='https:'?'https://d1.openx.org/ajs.php':'http://d1.openx.org/ajs.php');var m3_r = ... etc etc
I'm ok with jquery but not great with javascript, would really appreciate any help! Also if you want to see any other code.
Certainly this question was asked quite some time ago; however, the openX ajs.php file returns a document.write() function. If you use jQuery's $(document).ready() class method, it will overwrite your current page.
document.write() will only correctly execute (without overwriting your current page) if it is called during the page load procedure.
There's two ways to overcome this obstacle, and that would entail using AJAX (if your openX server is on the same URL domain as your website, or if you have server side scripting such as PHP, ASP, etc) or JSONP (if your openX server is on a different domain).
You'll have to setup a server side script with PHP, ASP, etc to have your jQuery call using AJAX/JSONP and have that server script load in the URL and return the contents of the document.write() function that the ajs.php file returns.