I have a code that asks a user to input a URL and append it to a div using javascript and it works fine. what I was trying to add was editing the user entered URL, specifically change the width and height of the iframe entered by the user then appending it. My current code is attached below. Any help is appreciated. Thanks in advance.
function input() {
globalThis.urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
document.getElementById("add_to_me").innerHTML += urlInput;
document.getElementsByTagName('iframe').width= "300px";
document.getElementsByTagName('iframe').height= "300px";
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
I think this is what you're trying to do;
function input() {
globalThis.urlInput="";
urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src",urlInput );
ifrm.style.width = "300px";
ifrm.style.height = "300px";
ifrm.style.frameborder = "0";
ifrm.allowFullScreen = true;
document.body.appendChild(ifrm);
}
<button onclick="input()">Input</button>
Basically what I do is I create the iframes dynamically and prompt multiple times for url, width and height which I then set on the newly created iframe DOM-Element.
As far as I know it is generally considered bad practice to use global variables. So I edited your code to inject the user input from user function input() into
appendiFrame(input).
Here's my extended code (consider the comments):
function input() {
// create local variable
var input = { url: '', width: '0', height: '0'} // creates dictionary containing input
input.url = prompt("Enter embed URL:")
if ( input.url == "") { // test if url was given
alert("No URL Inputted")
return // return if empty
}
input.width = prompt("Enter width:")
input.height = prompt("Enter height:")
appendiFrame(input)
}
function appendiFrame(input){
iframe = document.createElement('iframe') // create iframe dynamically
iframe.src = input.url;
iframe.width= input.width
iframe.height= input.height
document.getElementById('add_to_me').appendChild(iframe)
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
In order to test it you need to also enter the protocol (https) as part of the url. The site also must not send the X-Frame-Options: sameorigin HTTP-header as e.g. Google does or else your browser won't load the iframe.
You might also perform some checking whether the inputs entered are valid.
Related
Today I did a my text editor in iframe. I know that values from iframe doesn't send to database. My first idea relies on sending the values from iframe to the div, and that div data send to DataBase with the respective text formats.
function wlaczTrybEdycji(){
edytorTextowy.document.designMode = "On";
}
function execCmd(command){
edytorTextowy.document.execCommand(command, false, null);
}
function przeniesDane(){
var ramka = document.getElementById("ramka");
var dodiv = document.getElementById("daneIframe");
dodiv == ramka;
}
.textarea2{
width: 700px;
float: left;
height: 240px;
border: 2px solid black;
clear: both;
padding: 5px;
}
<body onload="wlaczTrybEdycji();">
<form action="" method="post">
<div class="EdytorTextowy">
<div class="przyciskiTextEdytor">
<button onclick="execCmd('bold');">BOLD</button>
</div>
<iframe name="edytorTextowy" class="textarea2" id="ramka"></iframe>
<div id="daneIframe">
</div>
<button type="submit" name="wyslijText">WYSLIJ</button><!-- here send from "daneIframe" to DB (PHP)-->
</div>
</form>
</body>
One important thing to understand about what you're doing is that the browser has rules about Cross-document communication.
A page inside an iframe is not allowed to access or modify the DOM of its parent and vice-versa unless both have the same origin. So putting it in a different way: document or script loaded from one origin is prevented from getting or setting properties of a document from another origin.
Here's the docs on Same-Origin Policy from MDN.
If the iframe and the page that loads it are of the same origin you should be able to do exactly what you're trying to do just fine. If not, then these documents need to be made available in the same origin to do so.
Hmm I understand now! You can get elements with ajax or javascript like so :
JavaScript for the Example
The JavaScript displayed here is just an example to show how to access to iframe elements.
// attach handlers once iframe is loaded
document.getElementById('ifrm').onload = function() {
// get reference to form to attach button onclick handlers
var form = document.getElementById('demoForm');
// set height of iframe and display value
form.elements.button1.onclick = function() {
var ifrm = document.getElementById('ifrm');
var ht = ifrm.style.height = '160px';
this.form.elements.display.value = 'The iframe\'s height is: ' + ht;
}
// increment and display counter variable contained in iframed document
form.elements['button2'].onclick = function() {
// get reference to iframe window
var win = document.getElementById('ifrm').contentWindow;
var counter = ++win.counter; // increment
this.form.elements['display'].value = 'counter in iframe is: ' + counter;
}
// reference form element in iframed document
form.elements.button3.onclick = function() {
var re = /[^-a-zA-Z!,'?\s]/g; // to filter out unwanted characters
var ifrm = document.getElementById('ifrm');
// reference to document in iframe
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
// get reference to greeting text box in iframed document
var fld = doc.forms['iframeDemoForm'].elements['greeting'];
var val = fld.value.replace(re, '');
// display value in text box
this.form.elements.display.value = 'The greeting is: ' + val;
}
form.elements.button4.onclick = function() {
// get reference to iframe window
var win = document.getElementById('ifrm').contentWindow;
win.clearGreeting(); // call function in iframed document
}
}
Or you can do something like this in jquery :
var content=$("iframe").contents().find('body').html();
//alert elements in iframe or show elements as a response in and div
alert(content);
I am trying to display a button if the src attribute of an iframe on the same page contains a certain text.
See jsFiddle for example.
I am basically trying to only show the "download MP3" button if the iframe has a valid soundcloud url as src attribute.
The one thing all valid soundcloud iframes have in common is: all src urls start with
//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F
You can get the dom element, and check it's src attribute.
Something like that:
const src = document.getElementById('ifrm').src;
if (src.indexOf('some')) {
console.log('YAY');
} else {
console.log('Not Yay')
}
<iframe src="https://some-site.com" id="ifrm" />
consider the following code snippet:
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var url = "//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"
if(src.indexOf(url) !=-1){ //this will return -1 if false
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
or you can use regular expression test function :
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var patt = //"/w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"/;
if(patt.test(src)){ // will return true if found
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
hope it helps
I'm just getting into javascript and so far enjoying the logic behind it but i have an issue with Firefox. basicly im generating my javascript from within a php function and its a NON SECURE pin code auth script.
So my php creates a call that passes variables pin number included, when called a modal popup with pinpad opens and the user inputs 4 digits, the pinpad onclick function adds the digits into a password field and after 4 clicks it compares it to a hidden field on the pinpad form, if it matches it calls another generated function to complete the success action, if no match pinpad frame turns red and a bypass button is enabled or they can try again.
This all works fine in Chrome, Opera and even IE but in Firefox it calls the success function after 4 digits even if they don't match the pin field.
Why could this be? Below is the function, but please remember I'm new so it could possibly be better written.
function add(text) {
var TheTextBox = document.pinform.elements['pin'];
var pincheckbox = document.pinform.elements['pincheck'];
var sidbox = document.pinform.elements['sid'];
TheTextBox.value = TheTextBox.value + text;
if (TheTextBox.value.length == 4) {
if (pinform.pin.value == pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
document.getElementById("bypass").innerHTML = "Bypass";
document.getElementById("bypass").disabled = false;
document.getElementById("calc").style.backgroundColor = 'red';
TheTextBox.value = '';
return false;
}
}
}
Found the answer by trial and error as usual lol.
i need to add document. in front of pinform.pincheck.value and pinform.pin.value
Thanks for the help offered.
Nick
if (TheTextBox.value.length == 4) {
if (doucment.pinform.pin.value == document.pinform.pincheck.value) {
var pinn = document.getElementById('sid').value;
eval('pinpass' + pinn + '();');
} else {
Basically, im making a javascript to refresh a page and it will find the price and buy the item when it goes up for the price desired.
I got it to work without the iframe, but I need to to work in the iframe, which is the problem ive reached.
If you went to this page: [ http://m.roblox.com/items/100933289/privatesales ]
and ran this code:
alert(document.getElementsByClassName('currency-robux')[0].innerHTML);
You would get an alert for the lowest price. In the code, this doesnt work (Hence, my problem.)
Try running the code below on this page to get it to work [ http://www.roblox.com/Junk-Bot-item?id=100933289 ]
var filePath = document.URL;
var itemid = filePath.slice(((filePath.search("="))+1));
var mobileRoot = 'http://m.roblox.com/items/';
var mobileEnd = '/privatesales';
var mobileFilePath = mobileRoot+itemid+mobileEnd;
var iframe2 = '<iframe id="frame" width="100%" height="1" scrolling="yes"></iframe>';
document.write(iframe2);
var iframe = parent.document.getElementById("frame");
iframe.height = 300;
iframe.width = 500;
iframe.src = mobileFilePath;
var price;
var snipe = false;
var lp = Number(prompt("Snipe Price?"));
document.title = "Sniping";
function takeOutCommas(s){
var str = s;
while ((str.indexOf(",")) !== -1){
str = str.replace(",","");
}
return str;
}
function load() {
if (snipe == false) {
tgs = iframe.contentDocument.getElementsByClassName('currency-robux');
price = Number((takeOutCommas(tgs[0].innerHTML)));
alert(price);
}
}
iframe.onload = load;
You might try having both pages — the one from "m.roblox.com" and the one from "www.roblox.com" — add the following up at the top of the head:
<script>
document.domain = "roblox.com";
</script>
Code from the different domains won't be allowed to look at each others page contents, but if you set the domains to the same suffix then it should work.
If you can't get it to work by sharing the same document.domain="roblox.com" code then you can try posting messages to the iframe.
Put this inside the iframe page:
window.addEventListener('message',function(e) {
});
In the parent page execute this to pass a message (can be a string or object, anything really) to the iframe:
document.getElementById("frame").contentWindow.postMessage({ "json_example": true }, "*");
Put this in the parent to listen for the message:
window.addEventListener("message", messageReceived, false);
function messageReceived(e) {
}
From inside the iframe posting a message back out:
window.parent.postMessage('Hello Parent Page','*');
I'm trying to show or hide divs based on user settings in a Windows 8 app. I have 2 divs in my html file:
<div id="fillBlank"><p>Fill in the Blank area</p></div>
<div id="multipleChoice"><p>Multiple choice area</p></div>
In the JavaScript file I have:
var answerStyle = "mc";
function showArea() {
if (answerStyle == "mc") {
// Multiple choice
multipleChoice.visible = true;
fillBlank.visible = false;
} else if (answerStyle == "fb") {
// Fill in the blank
multipleChoice.visible = false;
fillBlank.visible = true;
}
}
This doesn't work. Any suggestions? Thanks in advance.
One way to do this in JavaScript is to use the style property:
var fillBlank = document.getElementById("fillBlank");
fillBlank.style.display = "none";
Setting style.display to "" will make it visible using what ever the display time the element currently has set.
You're very close!
var answerStyle = "mc";
function showArea() {
if (answerStyle == "mc") {
// Multiple choice
multipleChoice.style.visibility ='visible';
fillBlank.style.visibility = 'hidden';
} else if (answerStyle == "fb") {
// Fill in the blank
multipleChoice.style.visibility = 'hidden';
fillBlank.style.visibility = 'visible';
}
}