Load external javascript file and create iframe [duplicate] - javascript

This question already has answers here:
Can you make a javascript function replace itself on the page with custom html?
(4 answers)
Closed 5 years ago.
I need to create a javascript that return a iframe tag.
the customer will paste a script in where the iframe need to be, and then the script should create a iframe.
Must be like this:
<script src="http://www.helloworld.com/script/loadcustomerframe.js" data-customer="14532"></script>
then the script should load a iframe to a url somewhere, and also i need to read the "data-customer".
I am a backend developer c#, not a frontend. I have try several days now, i cant get it to work.
Please help.
Thanks

Something like this should work:
$(document).ready(() => {
$("[data-customer]").each(function() {
let customerId = $(this).data("customer");
$(this).replaceWith(`<p>This is customer #${customerId}.</p>`);
// The following comment is an example of how you could use an iframe
//$(this).replaceWith(`<iframe src="http://example.org/customer/${customerId}>Hello!</iframe>`);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-customer="1"></div>
<div data-customer="2"></div>
<div data-customer="3"></div>
You'll only need to have the script appear once (most likely in your <head>) and it will replace any <div> that has a data-customer attribute. You simply just need to figure out the proper URL for your <iframe>.

Si basically your JS code will do the trick,
First need to create a JS code and host it into some server to get it by fetching it, so image that your JS code is hosted into https://www.mygreatjscode.com/myjscode.js
So your JS code will do the rest,
like this using pure JS (with not frameworks like jQuery etc), so your myjscode.js file will contain this:
//create an autoexec function
(function(){
var body = document.getElementByTagName("body");
body = body ? body : false;
if (body){
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "MY_CUSTOM_ID");
//here set the url that the iframe will be render
iframe.setAttribute("src", "https://stackoverflow.com/");
//finally insert into the body of page
body.appendChild(iframe);
}
})();
Finally you need to insert the Script Tag into your page like this
<script src="https://www.mygreatjscode.com/myjscode.js" data-customer="14532"></script>

Related

Inserting Javascript code into HTML via Javascript [duplicate]

This question already has answers here:
Dynamically adding script element to a div does not execute the script
(2 answers)
Closed 5 years ago.
I am trying to insert Javascript code into HTML via Javascript.
Inserting this code into HTML does not work, the code is not executed :
<script>
function callAlert(){
alert('test');
}
</script>
This code is executed :
<img src="xxx" onerror="alert('test')">
This does not call the function so the alert is not executed :
<img src="xxx" onerror="callAlert();">
Why onerror alert is executed and onerror calling function not?
You can no longer insert a <script> tag using el.innerHTML. This is a security issue that has been added fairly recently.
Go to this page:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
and scroll down to the Security considerations section.
It mentions that you can not add a <script> tag but it is not fool proof. Things like you describe can still cause script to run:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
If you really need to add new JavaScript from existing JavaScript you will need to do something like the following:
var s = document.createElement('script');
s.textContent = 'function callAlert(){alert(\'test\');}';
document.head.appendChild(s);
callAlert();
Try putting the script into the head of the page, it could be that the function is executed before it's defiend.
If this isn't working please tell what error your console returns.

I need help building an anchor <a that passes variables to PHP

I'm currently using javascript but switching to jQuery is OK.
Within the HTML is a <div id="domain">nares</div>. I need to pick out the "nares" and put it in an anchor tag to look like this: Listing.
So far the code looks like this:
<script type="text/javascript">
var dom = document.getElementById('domain').innerHTML;
openPage = function() {
location.href = "myCode.php?domain="+dom;
}
</script>
Link
To me this looks like it should work but instead when the page opens I get;
TypeError: null is not an object (evaluating
'document.getElementById('domain').innerHTML')
This is probably because the div has not yet been populated. However after population the error changes to:
XMLHttpRequest cannot load javascript:openPage(). Cross origin
requests are only supported for HTTP.
Which truthfully I don't understand. In any case using jQuery or just plain javascript how do I build this tag? I really need the modal part to work, its part of the UI for this project.
You should move your dom element into the function like so:
<a id="test" onclick="openPage()" rel="modal:open">Link </a>
<script type="text/javascript">
function openPage() {
var dom = document.getElementById('domain').innerHTML;
document.getElementById("test").href = "myCode.php?domain="+dom;
}
</script>
Also you should get your a tag then change the href...

Insert jquery code inside same jquery file only in a determined url

I have some jquery code (For a gallery) which is interacting in all my pages of my site, disturbing the layout of the site. Therefore I would like a determined jquery code to interact only in the gallery page. To avoid jquery submissions I want to keep all the jquery code in one file. Therefore I need to append, insert, add... a segment of the jquery code inside the same jquery file. For this I'm trying to use this code:
var url = window.location.href; // returns the full URL
if(/gallery/.test(url)) {
$('INSIDE THE SAME JQUERY FILE').addCONTENT('JQUERY CONTENT');
}
I want to avoid creaitng another file and adding the following:
var url = window.location.href; // returns the full URL
if(/gallery/.test(url)) {
$('head').append('<script src="js/gallery.js">');
}
I would like to use only one script call.
The answer to this question is the following:
if(/gallery/.test(window.location.href)) {
// JavaScript code you wish to add
}
This will add the code in the same file only if for this example you are in a URL with the word gallery in it.

Scripts not running when using get function in jquery

I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.

How can I dynamically add an <object> tag with JavaScript in IE?

I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly.
id ="SomeId"
classid = "CLSID:{GUID}"
codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"
Even a general working idea or method would be nice.
Thanks!
I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.
// something akin to this:
document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
That should work, it does just fine for me - I use it to embed Windows Media Player in a page.
UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's innerHTML property.
UPDATE: Apparently you need more help than I thought you needed? Maybe this will help:
Have your BODY tag look like this: <body onload="loadAppropriatePlugin()">
Have somewhere in your page, where you want this thing to load, an empty DIV tag with an id attribute of something like "Foo" or whatever.
Have code like this in a <script> tag in your <head> section:
function getIEVersion() { // or something like this
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(".", msie))) : 0);
}
function loadAppropriatePlugin() {
if(getIEVersion() != 0) { // this means we are in IE
document.getElementById("Foo").innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
} else {
// if you want to maybe do the same for FF and load that stuff...
}
}
Does that help?
var object = document.createelement('object')
object.setAttribute('id','name')
object.setAttribute('clssid','CLSID:{}')
And the same for other parameters.
Two ways.
1) Just do a document.write where ever you want it
<script type="text/javascript">
<!--
document.write("<object id=\"SomeId\" classid=\"CLSID:{GUID}\" codebase=\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\"></object>");
-->
</script>
2) Edit a tag's innerHTML property.
<div id="my-div"></div>
<script type="text/javascript">
<!--
document.getElementById("my-div").innerHTML = "<object id=\"SomeId\" classid=\"CLSID:{GUID}\" codebase=\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\"></object>";
-->
</script>
EDIT: Just a note, it is best to not use JavaScript to do this, since people with JavaScript enabled will never see the object. It would be better to just place it in your HTML.

Categories