button and form to change src of Iframe - javascript

I'm building a page that I want a form to be able to target the iframe and have the selected webpage be what displays in the iframe.
I'm only needing the iframe to display an external webpage, and a button to make it happen. Not actually passing any information form or to the form.
Thanks
EDIT: After the Information I learned here, and a few Google searches to expound on that knowledge I came up with this, it works nicely.
<html>
<head>
<title>Check Port 1935</title>
</head>
<body>
<iframe id="resultsFrame" src="http://helpdesk.mydomain.com/test/prompt.html" name=resultsFrame width="500" height="300"></iframe>
<p>The page will display information about Wowza if the port is open<br>
The page will time out after ~20 seconds or so if the port is closed</p>
<form id="frmTestRegion" method="GET">
<select id="SelectRegion" name="SelectRegion">
<option value="http://helpdesk.mydomain.com/test/prompt.html"></option>
<option value="http://ipaddress1:port/">USA</option>
<option value="http://ipaddress2:port/">Europe</option>
<option value="http://ipaddress3:port/">Australia</option>
<option value="http://ipaddress4:port/">Japan</option>
<option value="http://ipaddress5:port/">South America</option>
</select>
<button type="button" id="btnSubmit" onclick="testRegion();"/>Test Server</button>
<button type="button" onclick="refreshIframe('http://helpdesk.mydomain.com/test/prompt.html');">Refresh Results</button>
</form>
<script>
function testRegion() {
var my_select = document.getElementById("SelectRegion");
var new_url = my_select.options[my_select.selectedIndex].value;
document.getElementById('resultsFrame').src = new_url;
}
function refreshIframe(myurl) {
document.getElementById('resultsFrame').src = myurl;
}
</script>
</body>
</html>
Then i have the page at http://helpdesk.mydomain.com/test/prompt.html display this
Please select a server from the drop down menu</br>
Then click "Test Server"</br>
I learned a lot here, about how scripts and buttons work.
Thanks

Well to make things easier give your iframe an ID first:
<iframe id="resultsFrame" name=resultsframe></iframe>
Then in your function:
<script>
function testRegion() {
var my_select = document.getElementById("SelectRegion");
var new_url = my_select.options[my_select.selectedIndex].value;
document.getElementById('resultsFrame').src = new_url;
}
</script>
And your "submit" button (changing it to a button element will prevent it from actually submitting the form, which we don't need to do since we're just firing a function):
<button type="button" id="btnSubmit" onclick="testRegion();"/>Test Server</button>
EDIT (Responding to Updates in Question):
Regarding the issue with your refreshing the iframe button/function, the problem is your button. When a button is in a form, it will default to a submit button. So when you click it, it actually submits the form, and since you have no action specified on the form, it defaults to the same page. The query string in your URL is the form submission data. To prevent a button in a form from submitting when it is clicked, change its type attribute to "button":
<button type="button" onclick="refreshIframe();">Refresh Results</button>
Regarding a custom error message when the iframe fails to load the source -- browser security restrictions will prevent you from accessing the contents of the iframe. There isn't much you can do from the parent page to edit the iframe innards if you're loading a domain different from the requesting domain. I'd suggest creating a new server-side script as a "proxy", then have that script do the work of checking the URL to see if its open/closed, and return a response to your iframe. So instead of applying the source URL to the iframe directly, you'd source your own server-side script "mydomain.com/test-url.php?src=ipaddress1" and return the error from your own script.

Related

Fill input field inside an iframe when link outside of iframe is clicked

I have been trying to get this to work for 2 weeks now but I am stumped on this which is probably very simple. I am new to js.
I have multiple links on a page along with a form embedded in an iframe. Same domain, same page, both using https. The form is from a form script and is embedded in the page using:
<div id="my_placeholder"
data-formurl="https://www.example.com/forms/embed.php?id=7777"
data-formheight="1268"
data-paddingbottom="10">
</div>
<script src="https://www.example.com/forms/js/jquery.min.js"></script>
<script src="https://www.example.com/forms/js/jquery.postmessage.min.js"></script>
<script src="https://www.example.com/forms/js/form_loader.js"></script>
Using that code it automatically puts the form in an iframe. The input field ID within the form i'd like to fill is #element_11
So far, I have the following code which works exactly as I'd like but the generic form code is not in an iframe
Link1
<br />
Link2
<br />
Link3
<form>
<input type="text" id="element_11" />
</form>
<script type="text/javascript">
function reply_click(element)
{
document.getElementById('element_11').value = element.getAttribute('data-filled-value');
}
</script>
How can I accomplish this? I have searched and searched but every post I've come across wants to target the iframe and "submit" the form or "close" the iframe or "fill in one form and have it go to another form in an iframe".
Use .contents() to access the contents of an iframe.
function reply_click(element)
{
$("#iframeID").contents().find("#element_11").val(element.dataset.filledValue);
}
Replace iframeID with the actual ID of the iframe.

Upload dialog disappears, immediately after it appears, on web page, that I am creating

I am trying to use elninotech/uppload, as it looks like it will do what I want (give me a portable, easy to use, powerful file upload button). However when I click on the button, the upload dialog appears and disappears (press pause, in debugger, before pressing button, then single step. On 2nd step dialog appears, on 3rd step it disappears).
What am I doing wrong?
<html>
<body>
<form class="profile">
<button id="uploadButton">upload image</button>
</form>
<img id="profilePicImage"/>
</body>
<script src="https://unpkg.com/uppload/dist/uppload.min.js"></script>
<script>
const profilePicture = new Uppload({
value: "https://randomuser.me/api/portraits/men/17.jpg",
bind: ["#profilePicImage"],
call: ["form.profile button#uploadButton"],
//endpoint: "https://example.com/upload_backend",
allowedTypes: "image"
});
</script>
</html>
I found a very complex example on their website https://elninotech.github.io/uppload/ I spent some time debugging, and looking at their code. This is what I found.
An element may have the attribute data-uppload-button to mark it as an uppload button. I don't know how that can work with more than one button.
A default button in form dose not work (it causes the problem described in the question). Changing the button to a span works (but is un-intuitive to user). Changing the form to a div, works. Changing the button type to button works.
From the git-hub issue tracker https://github.com/elninotech/uppload/issues/21#issuecomment-445997614
When you have an HTML form element without a method, it defaults to GET. If it has a button inside it, the form assumes it's a submit button, and therefore refreshes the page on pressing it. This means that if you have button without a type="button", the page is refreshed. This means the original state is reverted and you don't see Uppload open up. That's why you need a type="button" on buttons you don't want to submit the page. Alternately, you can have a event.preventDefault() and return false on the onSubmit event on the form too.
Here is the working code:
<html>
<body>
<form class="profile">
<button type="button" id="uploadButton">upload image</button>
</form>
<img id="profilePicImage"/>
</body>
<script src="https://unpkg.com/uppload/dist/uppload.min.js"></script>
<script>
const profilePicture = new Uppload({
value: "https://randomuser.me/api/portraits/men/17.jpg",
bind: ["#profilePicImage"],
call: ["div.profile button#uploadButton"],
//endpoint: "https://example.com/upload_backend",
allowedTypes: "image",
services: ["upload", "camera", "link"],
crop: {
startSize: [100,100, "%"]
}
});
</script>
</html>
I have not yet tested with a working endpoint (server)

Redirect to a SubDirectory via Form Input in JavaScript

When this project was first started we thought it would be super easy but after two days of failure, we are stumped.
Environment: MacBookPro - WordPress with Thrive Themes Architect
Goal: Create a simple form that allows visitors to input the name of a subdirectory into a form that instantly redirects them to that subdirectory upon clicking on the submit button.
Purpose: When a partner gives out their website URL which includes a subdirectory name sometimes the person fails to put in the subdirectory name and they go to the main site instead. This form would make it easy for them to get to the right place so that the right partner gets proper credit.
Theories: Could the redirect be being blocked by Browser security protocols or something? Is the coding off in some way? Is the method flawed?
Three of Many Failed Coding Attempts:
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.href= "https://www.thewatercoach.com/" + subDirectory;
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.replace(subDirectory);
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subLink = document.getElementById("sub_Link");
var subDirectory= document.getElementById("sub_directory").value;
subLink.href = "https://www.theWaterCoach.com/" + subDirectory;
subLink.click();
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
<a id="sub_Link" href="https://www.theWaterCoach.com/">.</a>
Results: This Coding Example did work reliably with FireFox but not on Chrome or Safari. It does not work via Chrome on a PC either. For testing purposes, you can enter Becca into the text box.
Any ideas or solutions will be greatly appreciated!
The submit button is located inside a form tag. Therefore, when you click submit, the browser simply sends a GET request to your homepage. The Javascript code to redirect got executed, but then it is terminated right before the GET request is sent.
Solution: You have to prevent the form from being submitted. Find out how: read this stackoverflow question.

My form submission get blocked because the frame is sandboxed and the 'allow-forms' permission is not set

I'm trying to build a custom form and submission post for Hubspot.
I have the following code
HTML
<head>
<script src="prezzi-form-submit.js"></script>
</head>
<body>
<form class='form-inline' id='my-custom-form'>
<div class="form-group">
<input type='email' class='form-control' placeholder='Your email address' required>
</div>
<button class="btn btn-primary" type='submit'>Sign up</button>
</form>
<!-- Actual form that gets submitted to HubSpot -->
<div class="hidden" id='hubspot-form'>
<script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
<script>
hbspt.forms.create({
portalId: 'my-portal-id',
formId: '92b9b82a-0da2-4e23-8a30-04541c05ce6d',
onFormReady: function($form) {
$form.attr('target', 'hubspot-iframe');
}
});
</script>
<!-- iFrame that data will get submitted to. This hack stops the page redirect. -->
<iframe name="hubspot-iframe" id="hubspot-iframe" sandbox="allow-forms"></iframe>
</div>
</body>
JS (prezzi-form-submit.js)
// // Send form data to HubSpot from the client.
function submitToHubSpot(data) {
var $form = $('#hubspot-form form'),
k;
// Loop through each value and find a matching input.
// NOTE: Doesn't support checkbox/radio.
for (k in data) {
$form.find("input[name='" + k + "']").val(data[k]);
}
$("form input:submit").trigger("click");
}
// Here's how you'd use this.
$('#my-custom-form').on('submit', function() {
var formData = {};
$(this).serializeArray().forEach(function(data) {
formData[data.name] = data.value;
});
submitToHubSpot(formData);
// We sent the data. Now do whatever else you want.
alert('Gee, thanks Jonathan! Now I can focus on onboarding my customers with Appcues!');
window.location.href = 'http://appcues.com';
})
When I press the submit button, I get the following error in the console
Blocked form submission to " " because the form's frame is sandboxed
and the 'allow-forms' permission is not set.
As you can see I have the
sandbox="allow-forms"
set in the I frame but it isn't working.
How can I fix this error?
Sometimes when you click a link from an application, the tab opened will have javascript disabled/sandboxed.
Close the tab and reopen the same URL in a fresh tab, it might work.
Ran into the same problem with an iFrame form on Hubspot and got the same JS error. Discovered it has to do with the live preview using the HS Design tool.
In the drop down at the top there's the "Live preview with display options" then the "Preview without display options". It's the "preview with display options" selection that makes it "Sandboxed", try the one without. Hope this is helpful for someone.
Instead of setting the allow-form attribute in the html, set it within the .js using
el.setAttribute('sandbox', 'allow-forms');
It is because the frame itself is being sandboxed but the script is being called prior to the form being submitted which triggers submission of the frame but since the user wouldn't be able to submit, it wont call the iframe properties to respect the attribute set there

Open Google page in Javascript

I have the following code to open a google page and type "Hello" in the textbox.
The code opens the page but the textbox is empty.
Does anyone have an idea please ?
Thanks.
<html>
<head>
<script type="text/javascript">
function getValue()
{
var myWindow = window.open("http://www.google.com","_self")
myWindow.title = "Test"
var TextBox = myWindow.document.getElementsByName("lst-ib");
TextBox[0].value="Hello"
}
</script>
</head>
<body>
<form>
<input name="to" type="hidden" value="hoolah" />
<input type="button" onclick="getValue()" value="Get Value!" />
<form/>
</body>
</html>
You cannot:
Access the DOM of a page on a different origin
Access the DOM of a page from JavaScript that was running in the same window before you loaded the new page
What you want is impossible.
(If it was possible, it would be a security problem as your JavaScript would have access to personal data belonging to your visitors and stored on other websites.)
If I understand the question - you want to be able to pass a value to a Google search from your page. Rather than accessing the DOM of an external page - you are just trying to enter a value into the search term box on the google page.
All you have to do is append a query string to the Google url (such as "http://www.google.com?query=searchTerm" and it will pass the value to the search box on the google page.
I have slightly modified your code to show this - not how i would normally do it but I wanted to keep your code in place as much as possible so you can see whats going on.
I added a search term input and the onclick event opens the window and submits the query to Google. It could have been done as a form submit as well. Note that I put the JS at the bottom of the page - increases speed of page rendering - not important for this, but good practise movingforward. I also declared the variables together instead of using 2 'var's as well.
your code (slightly modified).
<html>
<head>
</head>
<body>
<form>
<input id="searchTerm" type="text" value="" placeholder="Search term"/>
<button type="button" onclick="getValue()">Search</button>
</form>
<script>
function getValue()
{
var term,myWindow;
term=document.getElementById('searchTerm').value;
myWindow = window.open("http://www.google.com?query="+term,"_self")
}
</script>
</body>
</html>

Categories