If this question cannot be answered, then I'm going to post a second, "fall back" question.
I have been writing javascript jsonp type apps where the client has to insert a single javascript line into wherever they want the app to show up on the web page. So far it's work out pretty well, but now I want to add one more GET variable to the js src attribute, and that is the present client's page url.
before:
<script id="myScript" type="text/javascript" src="http://www.mydomain.com/scripts/ds.js?cid=00000001&domain=clientdomain.com"></script>
But now for the new twist, I want to add the page url as a GET variable in the src, like so:
<script id="myScript" type="text/javascript" src="http://www.mydomain.com/scripts/ds.js?cid=00000001&domain=clientdomain.com&page="+document.URL></script>
If document.URL is placed between the script tag, I can do it (but that leads me to have to write a slightly larger and less elegant code block). Maybe javascript is not actually allowed in the attribute parameters of the tag, itself.
The usual way to do something like this is to build the tag itself in JavaScript. You can get an added benefit of asynchronous loading (although this can be a problem if you don't know how to handle asynchronous loading properly). For example:
<script>
(function(d){
var f=d.createElement('script'),s=d.getElementsByTagName('script')[0];
f.type='text/javascript';
f.async=true;
f.src='http://www.mydomain.com/scripts/ds.js?cid=00000001&domain=clientdomain.com&page='+encodeURI(document.location.href);
s.parentNode.insertBefore(f,s)
})(document)
</script>
Google Analytics uses similar code so you're in good company. And you're quite right that you can't do this directly inside a HTML tag.
Related
I'm using a low-code development platform called WaveMaker right now, and it gives you the option to customize the "markup" of the page (HTML, but you can't really edit <head>; the whole thing is kind of weird), the Javascript of the page, particularly with events like onpageload, etc., the style of the page (CSS), and the page's variables (JSON). I'm trying to embed Formstack forms, but every time the Markup section encounters a <script> tag, it deletes everything after the end of the tag. This is what the markup page looks like. I contacted support and they seemed to indicate that this was on purpose. Is there any way to make HTML run script included in-line without saying <script>? PS: I would be able to embed using iFrames, but for some reason the iFrames aren't working on the iPhone test program, even though they're working on the simulator.
What you can do is put it inside an HTML event attribute.
<body onload="/*your JS here*/">
</body>
If that does not work, try attaching onload to another HTML element or try one of the other event handlers (though I believe that they should have taken this into account as well)
How about this :
<body onload="javascript:(function(){
// you can place your code here it should run
alert('ok')
})()">
</body>
In Avatao's Senior Web Security Career Path, there is a hacking task, where you need to insert malicious javascript code - but the <script> is tag filtered (other tags aren't). Aenadon's answer gived me one solution:
<body onload="your JS here"> </body>
After submitting that, I checked the official solution, and I found that:
<img src="x" onerror=alert('xss')>
I'm trying to create a page adaptive share button using the page's current URL (since the page varies from our customer to customer numbers). In the following code, there is a "script" and in it the element I need to make use the current pages url, "data-url". Is that possible?
<script type="IN/Share" data-url="thispagesurl" data-counter="top"></script>
Instead of quotes would I use some sort of variable in javascript or aspx? I'm really not sure since I honestly don't know that much about js.
You may need to do something server side.
It's possible to access and modify the script tag: (Assuming yours is the first script tag on the page)
document.getElementsByTagName('script')[0].setAttribute('data-url', window.location.href)
However this most likely won't work as scripts will have already loaded their content
I am currently trying to implement the Google Tag Manager but I run into a problem since the GTM appends the tags right before the closing tag of the body.
Whenever I have a template that needs to call a bit of code from one of the scripts in the Google Tag Manager I get an undefined error. This is obvious since it does not matter where I place my script in my view, GTM will always come after it since it appends right before the closing body tag.
Is there any way to fix this behaviour and why does Google do it like this? I understand that it helps with non-blocking but they might as well just place async attributes on the scripts and it will almost do the same?
An example I have Facebook Pixel as one of my tags in GTM and I need to be able to make a specific event call when I am loading a certain page as my view.
fbq('track', 'Search');
Ofcourse this needs a fbq instance to begin with. This leave me with only one option and that is to try and place my script in my footer which is a general template and it will get messy.
Any workaround for this behaviour?
The issue you are facing is that the Facebook library is not completely loaded when you are calling your function.
One method would be to migrate your Facebook code to GTM trigger it on all pages
and fire your specific code on dom ready
You could also use the code from below and see when the _fbq.loaded variable is set to true.
https://gist.github.com/chrisjhoughton/1dc91dd7bd95717e08d3
You would have to create trigger based on this javascript variable.
Hope this helps
If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div> or adding some links.
Should this be put in the <body>, interspersed with HTML? Or should it be between the <head> and <body> elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?
If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go?
Just before the closing </body> tag is emerging as the best practice barring a specific requirement for it to be elsewhere (which there can sometimes be). It's the recommendation of the YUI folks, for instance, but it's not just them.
What order do things happen in - the order they are in the page or does HTML all happen before (non-) JS is run?
When a script tag is encountered, unless you use the defer or async attribute (and the browser supports them), all HTML parsing comes to a screeching halt and the script is downloaded and handed to the JavaScript interpreter. When the JavaScript interpreter finishes processing the script, the HTML parser can continue. It has to do this because the JavaScript can insert tokens into the HTML stream via document.write. This is also why you can load a script file and then load a second script file that relies on the first, and know that they'll get loaded in the right order. It's also why you can't access elements that are further down in the HTML stream from a script higher up in it unless you defer your code somehow (window.onload or the "DOM loaded" events many libraries support, such as jQuery's ready or Prototype's dom:loaded).
An upshot of this is that the typical practice of putting script tags in the head actually slows down the apparent load time of the page, unless those script tags need to be there for some reason. Hence the recommendation to put them just before the closing </body> tag.
There's a "gotcha" you have to watch for, though: If you have parts of the page that you want to respond to with JavaScript if the user has it enabled, loading your script at the very end leaves a brief but real race condition lying around: The user can interact with the page while your script is being downloaded. There are a variety of ways of handling that. My favorite is to detect whether JavaScript is enabled with inline script (not a separate file) in the head element and, if so, to put in a document-level handler for things where possible (you can do this with click events, for instance) which basically queues up or disables the click during that very brief period of time. That way, if JavaScript is enabled, you'll avoid the race condition, but if it isn't, any unobtrusive fallback you have in place will work.
The whole HTML file is executed in the order it is written, that means
<html>
<div id="ID"></div>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
</html>
changes the contents of the div, wherease
<html>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
<div id="ID"></div>
</html>
does not, because the JS code is executed before the div has loaded.
EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or
<body onload="...">
Alternatively if you're using a JS library such as jQuery, you can use
$(document).ready(function() {
...
});
Put them as functions in its own .js file which you include by <script src> at end of HTML <head> or <body>. If any of them needs to be executed during document load, call it using window.onload or whatever load function the JS library/framework offers, if you are using any.
As to the exact location, putting them in end of <head> allows them to be downloaded before the HTML page is been shown in browser and putting them in end of <body> allows the page to be shown a tad sooner because downloading the scripts will block the page rendering, thus it's a better speed experience.
However, IMO, it's a bit more robust to have the scripts downloaded before the page is rendered whenever you have some page elements which cannot be used without JS. In case of an impatient user this would otherwise lead to unusable elements.
I'd put it in a separate .js file and wrap the code so it is executed after the DOM is loaded. If you use a framework like jQuery or Prototype this should be easy.
For best performance place your JavaScript files at the BOTTOM of the HTML page you are serving.
To ensure that everything is set when you try to use it, execute only after the DOM is ready (there are multiple variations of this, my advice: Use a JavaScript Library).
You can put a script tag in the head, body, between the two, and more. You can put it most places but see this for a more in depth look.
I'm trying to dynamically insert the Tweetmeme button using Javascript. I'm currently using jQuery throughout the site. Here's the script that I'm using. I basically want to cycle through all the blog entries with a class of journal-entry and append the following JavaScript to the end. This Javascript comes straight from tweetmeme.com. This doesn't work for me though and it has something to do with the code between append(). It doesn't like the second set of script tags.
<script type="text/javascript">
$(document).ready(function() {
$('.journal-entry').each(function(index) {
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>');
});
});
</script>
Any help is appreciated.
Thanks.
Don't do this.
Inserting <script> HTML content into the DOM is unreliable: it works subtly differently in different browsers, and jQuery won't protect you from the differences.
In particularly, writing innerHTML never causes a <script> element's content to execute, but subsequently moving the <script> element from where it is to a new parent (which is part of jQuery's append process) may cause the script to execute, but not always (it depends on the browser).
In any case, it'll never work, because looking at button.js, it is calling document.write(). That function only makes sense to call at initial document parsing time; if you call it from an event afterwards, the call will simply replace the entire page content, destroying your existing page. A script that calls document.write() can only be run at document load time, from inside the execution path of a <script> element. You can't include the script in dynamically-created content at all, because it's not designed for it.
(If it makes you feel any better, it's barely designed at all; the button.js script is a badly broken load of old crap, including improper URL-escaping—using escape instead of the correct encodeURIComponent—and missing HTML-escaping. You may be better off well away from these total idiots.)
The closing </script> in the string in your append(...) call is closing the overall <script>
Try splitting it up into two strings. E.g:
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></'+'script>');