How can I create a javascript badge or widget? - javascript

I want to create a javascript badge that displays a list of links. We host the javascript on our domain. Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag. How do you implement something like this?

I would give the SCRIPT tag an ID and replace the script tag itself with the DIV + contents, making it so they only have to include one line of code. Something along the lines of the following:
<script id="my-script" src="http://example.com/my-script.js"></script>
In your script, you can swap out the SCRIPT tag for your DIV in one fell swoop, like so:
var scriptTag, myDiv;
scriptTag = document.getElementById('my-script');
myDiv = document.createElement('DIV');
myDiv.innerHTML = '<p>Wow, cool!</p>';
scriptTag.parentNode.replaceChild(myDiv, scriptTag);

just as you say, have them put a div at the bottom of their page:
<div id="mywidget"></div>
then have them link to your javascript:
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
then have them alter their body tag, or onload to call your script
<script type="text/javascript">
document.body.onload = loadYourWidget();
</script>

You do not necessary need an initial div to fill with you link list.
Simply create the div using document.write at the place where the script is placed.
<script type="text/javascript" src="http://domain.com/badge.js"></script>
... and in your script:
var links = [
'One',
'Two',
'Three'
];
document.write("<div>" + links.join(", ") + "</div>");
Another benefit is that you do not have to wait for the page to be fully loaded.

Like #Owen said, except why not craft your javascript so that
<script type="text/javascript" src="http://yourdomain.com/mywidget.js"></script>
does the work of populating <div id="mywidget"></div> on its own, thus negating the need for them to call loadYourWidget() from their DOM load if you include the script tag right after the mywidget div in the html source. This isn't really a best practice, but I think it'll work.
Example for your mywidget.js code:
document.getElementById('mywidget').innerHTML = "<a href=''>LinkOne</a> <a href=''>LinkTwo</a>";

It took me some time to find this answer on Stackexchange because I was using different search terms. I believe that the link suggested there is a more complete answer than the ones already given here:
How to build a web widget (using jQuery)
It covers:
ensure the widget’s code doesn’t accidentally mess up with the rest of the page,
dynamically load external CSS and JavaScript files,
bypass browsers’ single-origin policy using JSONP.

Related

Force browser to reload javascript files

I tried like this
<script type="text/javascript" src="myfile.js"?+Date.now()></script>
In browser it is showing as it is.
I want to add some timestamp to each js files.
i.e.,
<script type="text/javascript" src="myfile.js"?+5671836294></script>
Thanks in advance.
You can't randomly stick JavaScript anywhere you like in HTML.
When you are in the middle of an HTML start tag you can either:
End the tag with >
Write an attribute
JavaScript does not belong there.
If you want to generate an HTML attribute value dynamically when the element is created, then you must create the entire element with JavaScript.
e.g.
<script>
var s = document.createElement("script");
s.src = "myfile.js"?+Date.now();
document.head.appendChild(s);
</script>
… but you'd probably be better of solving this problem by properly configuring your HTTP headers for the script instead.
Refresh the page or rewrite the script tag and append it to the bottom of the body.
But once a page is loaded, it is loaded. You have to redeclare to overwrite.

Can't append script element to head

Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)

Browsers bug on document.write

I have multiple widgets like this
var c2409 = "<div class="products">PRODUCT1 PRODUCT2 PRODUCT4 ...</div>";
document.write(c2409)
And I call this
<script src="website/getjswidget.aspx?cid=xxxx-xxxx-xxx-xxxx"></script>
Now looks like sometime after I clear the cache, this replace everything in my html and I get a blank page only with this div from my widget.
Any other solutions to replace document.write?
This is by design.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
Source
If you want to append data to your webpage, use this:
document.body.innerHTML += 'your HTML code to add'
Edit: If you want to show this in a particular element, you can do something like this:
<!-- HTML element -->
<div id="myData"></div>
<!- Javascript code -->
document.getElementById('myData').innerHTML += 'your HTML'
Edit 2 (After some searching): You can get the current script element by using document.currentScript and then perhaps use Node.insertBefore to create a div right before that script tag, to put your data in.
Edit 3: Apparently document.currentScript doesn't work in IE. But this answer may help.

Print Javascript in Javascript?

I am in the process of making an addon for a software that basically allows you to have 'responsive' adverts, by checking the page size with javascript and then outputting the relevant ad code to the screen.
This works fine for text ad codes, however I've hit a snag when the ad code is javascript - I can't get the user-provided javascript to output to the page and be executed.
Is this possible at all?
Here is some example code:
<div id="admanagerresponsive">
<script type="text/javascript">
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;
if (adWidth >= 728) {
<output ad code>
}
</script>
</div>
The code above will be directly in the page.
Is such a thing possible?
EDIT:
could be any advertiser's code, such as adsense. It'll be user provided, and will be standard html. However, it could contain tags, and these will need to be rendered and outputted correctly...
If you really need to inject add html code containing script tags and you are award of the security problems, i suggest to use a library like jQuery that takes care about the cross browser issues with executing <script> tags added later.
Additionally you need to take care about various pitfalls like:
Html paring is done before script parsing, so no matter where a </script> appears this will immediately end your script.
The examples are important for the situations where you have that code as inline script inside your html page.
Example 1:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
// if you add </script> <b>this is visible as html</b> and everything below is not script anymore
}
</script>
Example 2:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</script>";//the same problem here everything behind the closing script tag is html and not script anymore
}
</script>
So if you need to have some script to inject there you need to make the </script> not to be detectable by the html parser:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</sc"+"ript>";//that way the html parser does not detect the closing script tag
}
</script>
A better solution is not to use inline script at all, not only for that reason, but because you should always keep css, js and html separated.
Break it into two ideas. From your HTML above, just call a js function you wrote somewhere else. Initially have that js function be an alert, to verify that works.
Once that works, you have the problem: how can I get custom js for a page? The answer to that is hopefully that you can create and load a (one-off, custom) js file the same way you create an html file. Or, libraries such as now.js could help. Or, there is a script portion of your html page that you understand how to assemble to include the js.
You could even preload all your size possibilities, then have the js routine from the first paragraph pick the right routine to call,

How can I append a new element in place in JavaScript?

I've created a JavaScript script that can be pasted on someone's page to create an iFrame. I would like for the person to be able to paste the script where they would like the iFrame to appear.
However, I can't figure out how to append the DOM created iFrame to the location where the script has been pasted. It always appends it to the very bottom of the body.
How do I append in place?
Mm. You could do:
document.write("<div id='iframecontainer'></div>");
document.getElementById('iframecontainer').innerHTML = '...';
But that feels ugly/wrong in a lot of different levels. I am not aware of any other alternatives, though.
EDIT: Actually, a quick google search revealed this artlcle which discusses why document.write is ugly and a nice alternative for the particular pickle you're in: Give your script tag an ID!
<script id="iframeinserter" src=".."></script>
And then you can get a reference to the script tag and insert the iframe before it:
var newcontent = document.createElement('iframe');
var scr = document.getElementById('iframeinserter');
scr.parentNode.insertBefore(newcontent, scr);
Paulo's answer can also be done without the ID, by simply looking for the last <script> element. This must be the script block we're in, because JavaScript guarantees all content past the closing tag of the current script block has not yet been parsed(*):
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(d, script);
This can be put in an onload/ready function if you like, but if so the ‘var script’ must be calculated at include-time and not in the ready function (when that executes, more <script>s will have been parsed).
(*: except in the case of <script defer>.)
If the user can give an id of an element that will be where the iframe should be, then it would be possible to just use css to move the iframe to where it should be on the page.

Categories