Javascript (Remote include) : HTML Elements creation on-the-fly? [duplicate] - javascript

This question already has answers here:
Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
(4 answers)
Closed 6 years ago.
I'm trying to make a floating HTML button, along with the interaction on it (like: Popping up a form when clicked) by letting the people just EMBED some Javascript inside their Page.
So it's like, my HTML Elements should be generated on top of their page (at different domain) remotely.
For example, i have seen something like Uservoice Feedback Button and Form, it looks like:
We can have that Button generated on our site. The only thing we need to do is to embed their Javascript in our page:
<!-- USERVOICE -->
<script type="text/rocketscript">
var uvOptions = {};
(function() {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/xxxxxxxxxxxxxxxxxxxxx.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>
I tried this
Then in order to achieve similar thing, i tried with my own 2 domains. On my Webpage at www.domain-a.com, i embed:
<script type="text/javascript">
(function() {
var myButtonJS = document.createElement('script'); myButtonJS.type = 'text/javascript'; myButtonJS.setAttribute('defer', 'defer');
myButtonJS.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.domain-b.com/myButton.js?3';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(myButtonJS, s);
})();
</script>
On the www.domain-b.com, inside the myButton.js:
document.write('<div style="z-index:99999999;padding:5px 10px 2px 10px;border:1px solid #000000;position: fixed;bottom: 10px;right: 10px;_position:absolute;_top: expression(offsetParent.scrollTop+document.documentElement.offsetHeight-60);direction:ltr;background:#7fff00;">Click me!</div>');
But when i run, http://www.domain-a.com, the browser says:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
So please kindly let me know:
What are the standard (proper) ways to achieve such ones?
(In other words) how do i properly generate the HTML elements on top of remote sites, when they include the Javascript i provided to them?
Thanks all :)

IMHO, the better way to do it is create the element on the fly from your externa js then load the script in the body of the html, that way you are sure that the document is loaded and then just hook in the body of document e.g:
document.getElementsByTagName('body')[0]
in your external script. then append your element there. :)

You can create A DOM element, use innerHTML to set its contents ant then attach to the DOM when the content is ready:
var myElement = document.createElement('div');
myElement.innerHTML = '<div style="z-index:99999999;padding:5px 10px 2px 10px;border:1px solid #000000;position: fixed;bottom: 10px;right: 10px;_position:absolute;_top: expression(offsetParent.scrollTop+document.documentElement.offsetHeight-60);direction:ltr;background:#7fff00;">Click me!</div>';
document.addEventListener("DOMContentLoaded", function() {
document.body.appendChild(myElement);
});

Related

running a script inside index.html with some conditions [duplicate]

This question already has answers here:
Dynamically add script tag with src that may include document.write
(16 answers)
Closed 3 years ago.
We have this script which we want to run only if user agent is ReactSnap. I tried doing this but it does not seem to be working.
<script>
if(navigator.userAgent!=='ReactSnap'){
<script src='//cdnt.netcoresmartech.com/smartechclient.js'</script>
}
</script>
The operator you are using in your conditional statement - !== is checking to see if the condition is not true.
The correct syntax is if(navigator.userAgent=="ReactSnap")
You are also trying to write html in a javascript context.
You should create your script tag using javascript, like the below example:
if(navigator.userAgent=="ReactSnap"){ // check userAgent
var script = document.createElement("script"); // create a script tag
script.setAttribute("type","text/javascript"); // set type to js
script.setAttribute("src", "//cdnt.netcoresmartech.com/smartechclient.js") // define src for script tag
document.head.appendChild(script); // load script into document head, or change this to a specific location
}
This solution waits to add the script element to the page until we know the condition is true (tested in Chrome):
<body>
<div>Page content goes here</div>
<script>
let conditionalScript = document.createElement("script");
conditionalScript.innerHTML = "alert('woo!')";
// (But set .src instead of .innerHTML)
let userAgent = 'ReactSnap';
if(userAgent == 'ReactSnap'){
// (But check `navigator.userAgent` instead of `userAgent`)
document.querySelector("body").appendChild(conditionalScript);
}
</script>
</body>
I'd suggest using createElement, changing the source with setAttribute and appending it to the head like this.
if(navigator.userAgent!=='ReactSnap'){
let smartTech = document.createElement('script');
smartTech.setAttribute('src', '//cdnt.netcoresmartech.com/smartechclient.js');
document.head.appendChild(smartTech);
}
You can try something like this:
<script>
if(navigator.userAgent=='ReactSnap'){
var script = document.createElement('script');
script.src = "//cdnt.netcoresmartech.com/smartechclient.js";
document.head.appendChild(script);
}
</script>

Dynamically insert script tag? [duplicate]

This question already has answers here:
How to append <script></script> in JavaScript? [duplicate]
(6 answers)
Closed 4 years ago.
So i have this script tag
<script async="async" data-cfasync="false" src=""></script>
That I'd like to be able to insert dynamically. I've tried setting it to a variable,
let scriptTag = '<script async="async" data-cfasync="false" src=""></script>';
and adding it using innerHTML to my content div but that doesn't seem to work. I know I'm going about this very wrong and part of me thinks this probably isn't even possible.
The reason I want to do this is so that I can turn ads on and off for testing purposes so my views during testing don't affect the analytics, is this something I should even be worrying about or is it negligible. I just know that I've been banned from chartboost for exactly this without having a testing variable that turned ads on and off.
Edit: Yes this is similar to other questions but those don't address using attributes like 'data-cfasync'. Mandalina and supra28 nailed it on the head.
It seems you are not adding your script tag correctly.
Here is one way you can do it:
const script = document.createElement("script");
script.type = "text/javascript";
script.src = "";
script.async = true;
script.dataset.cfasync = false;
document.body.appendChild(script);
script.addEventListener("load", () => {
console.log("Script added successfully");
resolve();
});
Try this function:
(function () {
if (typeof window.R === 'undefined') {
var s = document.createElement('script');
s.setAttribute('src', 'source goes here!');
document.body.appendChild(s); // this appends the script to the body you can also use document.head.appendChild(s) to append to the head
}
}());

Appending Script to DOM without JQUERY [duplicate]

This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 8 years ago.
The only way to fix it was using google chrome/IE10+ Just can't make it work on IE8.
I'm trying to append some Script to my web page, but i don't want to use any Jquery.
This DOES work, but it make use of jquery on the 3rd line.
var element = document.getElementById("contentSCRIPT");
element.parentNode.removeChild(element); // this removes the div and all the javascript inside it
$('<div id="contentSCRIPT"></div>').appendTo(document.getElementById("main")); // this adds again the content to the page
$('<script>' + document.getElementById("textSCRIPT").value + ' ;</' + 'script>').appendTo(document.getElementById("contentSCRIPT")); // in here i try to add the javascript code back to the content.
I tryied:
var content = document.createTextNode('<div id="contentSCRIPT"></div>');
document.getElementById("main").appendChild(content);
but it adds my script (content) as HTML not code.
any solutions?
Thanks!
Edit:
I have to create the contentScript cuz i want to delete the script from the page and add another multiple times.
I tryied
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
document.getElementById('contentSCRIPT').innerHTML = document.getElementById('textoSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
But again, this adds the code as an HTML (shows like a label on the page) and don't add to the DOM.
$('<div id="contentSCRIPT"></div>') can be written as follows in javascript:
var contentScript = document.createElement("div");
contentScript.setAttribute("id", "contentSCRIPT");
To do jQuery's appendTo, you want instead to appendChild on the parent:
document.getElementById("main").appendChild(contentScript);
Similarly, for the fourth line:
var script = document.createElement("script");
script.innerHTML = document.getElementById('textSCRIPT').value;
contentScript.appendChild(script);
EDIT
Based on your edited information, you don't need to create the div to hold the contentScript. Simply put an id on the script instead:
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
contentScript.innerHTML = document.getElementById('textSCRIPT').value;
document.getElementById("main").appendChild(contentScript);
You can create a script element and append it to the document:
var script = document.body.appendChild(document.createElement('script'));
script.text = '/* CODE */';
As a response to your edit: You can remove a script element from the DOM, but you can't remove the script itself.
A live demo at jsFiddle.
var script = document.createElement("script");
var contentScript = document.createElement("div");
contentScript.setAttribute("id", "contentSCRIPT");
script.innerHTML = document.getElementById('textSCRIPT').value;
contentScript.appendChild(script);
You can add a script tag programatically by simply adding the script tag:
var scriptTag = document.getElementsByTagName("head")[0].appendChild(document.createElement("script"));
scriptTag.innerHTML = document.getElementById("textSCRIPT").value;
Change "head" to "body" if you want to add the script to the body.

Place a script immediately after the opening <body> tag

I would like to place a Google tag manager script and according to Google Tag documentation, the script should be placed immediately after the opening tag.
Since we cannot change the source code, we have to append the script using the following code snippet.
<script type="text/javascript">
(function () {
var url = "path/to/js/file";
var gtm = document.createElement('script');
gtm.type = 'text/javascript';
gtm.async = true;
gtm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + url;
var s = document.getElementsByTagName('body')[0];
s.parentNode.insertBefore(gtm, s);
})();
</script>
It is almost the same as Google analytics script snippet. Now the script is appended right before the body tag. I am not sure if using jQuery method insertAfter is the proper way to do it or if there is a better way!
I appreciate your kind help.
Actually your code inserts script between the head and body tags. Use this instead:
var s = document.body.firstChild;
s.parentNode.insertBefore(gtm, s);
You can use Node.insertBefore for this:
var body = document.getElementsByTagName("body")[0];
body.insertBefore(gtm, body.firstChild);
This works even if body tag has no firstChild.
This Q is not relevant anymore (DEC 2021), since GTM change the Setup and install of Tag Manager:
On the "new" setup you should:
Place the <script> code snippet in the <head> of your web page's HTML output, preferably as close to the opening <head> tag as
possible, but below any dataLayer declarations.
**Additionally - Place the <noscript> code snippet immediately after the tag in your HTML output.
https://support.google.com/tagmanager/answer/6103696
About <noscript> no meaning to add <noscript> by any Javascript code (noscript works only in browsers when JavaScript is off).
let html = '<p>Your HTML code here</p>';
document.body.insertAdjacentHTML('afterbegin', html);
The insertAdjacentHTML method allows you to insert an HTML string at a specified position relative to an element. In this case, we use 'afterbegin' to insert the HTML just after the opening tag.
I think you can try this out - appendChild
document.getElementsByTagName("body")[0].appendChild(gtm);
Try this:
var script = 'The script content here'; // Add your JS as a string,
var url = 'path/to/js/file'; // Or link to the file.
var scriptNode = document.createElement('script'); // Create a script Element
scriptnode.setAttribute('type', "text/javascript"); // Set the Element's `type` attribute.
// Either:
scriptNode.appendChild(document.createTextNode(script)); // Add the text to the script Element.
// Or:
scriptNode.setAttribute('src', url); // Link to the script
// Place the script Element before the first child of the body.
document.body.insertBefore(scriptNode , document.body.firstChild);
So, basically, use insertBefore
If you are utilizing jQuery, you may be able to use .prepend().
(function () {
var url = "path/to/js/file";
var gtm = document.createElement('script');
gtm.type = 'text/javascript';
gtm.async = true;
gtm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + url;
$('body').prepend(gtm);
})();
Can you have an element in your body tag as first element, and append the script just before it. Use yourFirstElementIdfromBodyTag.before(here is your appended code goes) ..
For Example
<body>
<your first element> like <input type="hidden" id="hidA" />
//rest code goes here
</body>
Now as suggested use $('#hidA').before('the script code') . I am sure it will append the script just after <body>.

Executing a javascript that is injected as a script element via bookmarklet?

I am using bookmarklet to inject a element in document with a custom JS script file. I did it like this:
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = true;
newscript.src = 'http://www.myurl.com/my_js_script.js';
var oldscript = document.getElementsByTagName('script')[0];
oldscript.parentNode.insertBefore(newscript, oldscript);
But I can't figure out how to actually execute it. Can someone tell me how can I execute that JS file?
Note: Since this can be a Greasemonkey script as well, I am tagging this question for Greasemonkey as well.
Script tags are automatically downloaded and executed when they're added to the document. Note, however, that the script you're using may fail if the document you're injecting into doesn't already contain any <script> tags, as oldscript will be undefined.

Categories

Resources