Taking HTML content from other URL pages with JavaScript - javascript

I want my app to take text from other web pages!
If I insert the word "computer" I want to go to the URL of Cambridge's website and to take data I need.
insertingNewWord(insertedWord){
var pageHTML = "https://dictionary.cambridge.org/dictionary/english/"+insertedWord;
var definition = pageHTML.getElementByClasName("def-head");
return definition;
}
Any idea how I could take any tag by Class or ID name from another page, and printed in my app.
If I get a solution in ReactJs that would be even better.

One option is to use an <iframe>
<input type="text"><input type="button" value="search dictionary"><br>
<iframe width="400" height="300"></iframe>
<script>
const [input, button] = document.querySelectorAll('input');
const iframe = document.querySelector('iframe');
button.addEventListener('click', e => {
iframe.src = "https://dictionary.cambridge.org/dictionary/english/" + input.value;
})
</script>

Related

Pass query parameters to embeded iframe with javascript

I do not know much Javascript and I am trying to pass query string parameters to an embedded iframe.
Here is the url I am trying to retrieve query parameters from:
https://usslc.clickfunnels.com/optin1612360116340?contactId=924408&inf_contact_key=ea845fcb8c29d976c0755e8b56134056cc0558ed5d4c28cbfab114022b1ec50d&inf_field_BrowserLanguage=en-US%2Cen%3Bq%3D0.9&inf_field_FirstName=PG2&inf_field_Email=preston%2Btest2%40behavioralmedia.com&inf_field_Phone1=5554445555
Here is the code I need for the iframe:
<iframe src="https://app.squarespacescheduling.com/schedule.php?owner=21917237&appointmentType=20129186" title="Schedule Appointment" width="100%" height="800" frameBorder="0"></iframe><script src="https://embed.acuityscheduling.com/js/embed.js" type="text/javascript"></script>
This is what I have been working on and not getting any luck with:
<iframe id="myIframe" title="Schedule Appointment" width="100%" height="800" frameBorder="0"></iframe>
<script src="https://embed.acuityscheduling.com/js/embed.js" type="text/javascript">
let myIframe = document.getElementById("myIframe");
let src = "https://app.squarespacescheduling.com/schedule.php?owner=21917237&appointmentType=20129186"
let url = window.location.href;
let name = url.searchParams.get("inf_field_FirstName");
let email = url.searchParams.get("inf_field_Email")
let phone = url.searchParams.get("inf_field_Phone1")
let adsURL = src+"&firstName="+name+"&email="+email+"&phone="+phone;
myIframe.src = adsURL;
</script>
Again, I am a total noob with stuff like this so sorry if this is real bush league.
What is the best way to have the name, phone, and email prepopulate in the iframe?
Thanks!
Accessing an iframe that already exists on the page can be tough, if not impossible.
If you only need to have the desired fields w/ the iframe on page load then you could instead generate the iframe in the script tag and append it to the document like so:
<div id="frameWrapper"></div>
<script>
const url = window.location.href;
const frameWrapper = document.getElementById('frameWrapper');
const BASE_URL = 'https://app.squarespacescheduling.com/schedule.php?owner=21917237&appointmentType=20129186';
const frameElem = document.createElement("iframe");
frameElem.src = `${BASE_URL}` +
`&name=${url.searchParams.get("inf_field_FirstName")}` +
`&email=${url.searchParams.get("inf_field_Email")}` +
`&phone=${url.searchParams.get("inf_field_Phone1")}`;
frameElem.name = url.searchParams.get("inf_field_FirstName");
frameElem.title = "Schedule Appointment"
frameElem.style.height = "100%";
frameElem.style.width = "100%";
frameContainer.appendChild(frameElem);
</script>
In this case we are just replacing the iframe with a wrapper DIV, assembling the iframe in our script tag and appending it to the wrapper.

create the variable link as a hyperlink javascript

create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/

Generating a Unique Id for each Iframe, or building an Iframe out of DOM nodes

I need to set a unique Id for each Iframe so they render correctly. I have a renderId variable that increments. I'm trying to append that to the Iframe Id.
document.getElementById('iframe-test' + renderId);
Entire code block here:
let renderId = 0;
const render = post => {
renderId++;
const node = document.createElement('div');
node.innerHTML = `
<h2 class="centered">
<a href="${post.link}">
<br>
<iframe id="iframe-test" width="100%" min-height="100%" src="">
</iframe>
<br>
${post.title}
</a>
<br><br>
</h2>`;
app.appendChild(node);
document.getElementById('iframe-test' + renderId);
No videos are showing. I've tried changing the quotes on this line:
<iframe id="iframe-test" width="100%" min-height="100%" src="">
I need some extra steps before this line, but I'm not sure what.
document.getElementById('iframe-test' + renderId);
Full app: http://codepen.io/Teeke/pen/BWROeW
'<iframe id="iframe-test"'+renderId.toString()+' width="100%" min-height="100%" src="">' EDIT: You just forgot to give a different Id to each div. You was looking for an id that was not assigned so I added the renderId.toString. Maybe it will work without toString. Not sure
Create your 'unique' id in a variable at the top of the function:
let renderId = 0;
const render = post => {
renderId++;
const iframeId = `iframe-test-${renderId}`;
const node = document.createElement('div');
node.innerHTML = `<h2 class="centered">
<a href="${post.link}"><br>
<iframe id="iframe-test" width="100%" min-height="100%" src="">
</iframe>
<br>${post.title}
</a>
<br><br>
</h2>`;
app.appendChild(node);
document.getElementById(iframeId);
}
Alternatively, you could use the YouTube reference as the id like this:
// post.link (https://www.youtube.com/watch?v=TmIo702wjm4)
const uniqueId = `iframe-test-${post.link.substr(post.link.lastIndexOf('v=') +2)}`;
// iframe-test-TmIo702wjm4
I ended up building the iframe out of DOM nodes. This way I could build a easily repeating iframe without having to generate a unique ID for each frame. This doesn't actually generate an ID as per the original question, but it does allow you to copy an Iframe div with no unique ID issues. I amended the title of the question to reflect this broader solution.
HTML:
<div id="app"></div>
JS:
const app = document.querySelector('#app');
const render = post => {
const node = document.createElement('div');
node.innerHTML= `${post.title}`;
node.className= 'clip-title';
app.appendChild(node);
var a = document.createElement('iframe');
a.className = "clip-content"
a.src = "https://www.youtube.com/embed/" + strippedURL; //add your iframe path here
a.width = "100%";
a.height = "100%";
a.padding = "500px";
app.style.textAlign = "center";
document.querySelector('#app').appendChild(a);

How can I search iframe content (text) using an input field that is on the parent page?

Yes, I know something like this has been asked over here before and I have searched but the one that is closest to what I'm trying to achieve doesn't have an answer ( Search iframe content with jquery and input element on parent page ) and the one that does is making use of nested iframes ( Access the content of a nested Iframe ) and I didn't quite understand the solution (VERY new with javascript so please bear with me). Honestly, it's getting a bit frustrating (it's quite late over here) so I thought I might as well ask.
I have an iframe that displays a page from my site therefore the page is from the same domain. What I would like to do is to search the iframe for some text using javascript (not jquery). The search input box, however, is on the parent page.
I've done something similar to this before by putting the search input box in the page displayed in the iframe instead ( I followed this tutorial: http://help.dottoro.com/ljkjvqqo.php ) but now I need to have the search input box on the parent page because I going to make it "sticky" so that it will follow the user as they scroll down the page. I've resized the parent page height to be the same as the length of the page in the iframe by also using javascript.
So, my question is: How can I use javascript to search text that is in the iframe by using a search input box that is on the parent page?
My HTML so far:
<input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" value="Go"/>
<iframe id='iframe2' src="http://example.com/files/<?php echo $filename;?>" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" onload="AdjustIframeHeightOnLoad()"></iframe>
<script type="text/javascript">
function AdjustIframeHeightOnLoad() { document.getElementById("iframe2").style.height = document.getElementById("iframe2").contentWindow.document.body.scrollHeight + "px"; }
function AdjustIframeHeight(i) { document.getElementById("iframe2").style.height = parseInt(i) + "px"; }
Not sure how to move on from there. I'd really appreciate some help.
Thanks in advance!
EDIT:
The search works now (saw that I put the javascript above the html so I put it under it to get it working) so this is what I want to do with the search results:
I intend to use the search box to enter a page number such that when the user clicks "Go" the search will look for that page and scroll the user down to where the result (that is, the page number) is.
EDIT 2: I just thought I'd mention that my page numbers are written like this: -2- for page 2, -3- for page 3, etc.
I believe this is the solution you need,
HTML:
<!--added an id of search to the input element-->
<input id="search" type="text" name="page_no" size="3"/>
<!--changed input type to button and added an id of go-->
<input id="go" type="button" name="goto" value="Go"/>
<iframe id='iframe2' src="iframe.html" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe>
Javascript(make sure the iframe is in the same domain):
//on click event for the button with an id of go
var go = document.getElementById("go").onclick = function(){//begin function
//get the search value
var search = document.getElementById("search").value;
//get the html of the iframe(must be in the same domain)
var iframe = document.getElementById("iframe2").contentDocument.body;
/*create a new RegExp object using search variable as a parameter,
the g option is passed in so it will find more than one occurence of the
search parameter*/
var result = new RegExp(search, 'g');
//set the html of the iframe making the found items bold
iframe.innerHTML = iframe.innerHTML.replace(result,"<b>" + search + "</b>" );
};//end function
Here is a link that will explain some additional flags you can use with the RegExp object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Below is an improved version of Javascript to scroll to Page Number.
Place it inside of your on click event for the go button. The code requires that you place an id with the page number inside of an element at the top of each page. Example <h3 id="3">Page 3</h3>.
//get the search value
var search = document.getElementById("search").value;
//get the id of the search term
var iframe = document.getElementById("iframe2");
//the url of the page loaded in the iframe
var iframeURL = "iframe.html";
//set the source of iframe appending a link to an element id
iframe.src = iframeURL + "#" + search;
Solved! Thanks Larry Lane for your help.
Here is the present Javascript. Hope it helps someone.
<script type="text/javascript">//on click event for the button with an id of go
var go = document.getElementById("go").onclick = function(){//begin function
//get the search value
var search = document.getElementById("search").value;
//put hyphens for the page number
var pagehyph = '-' + search + '-';
//get the html of the iframe(must be in the same domain)
var iframe = document.getElementById("iframe2").contentDocument.body;
//remove the hash from the iframe src if there is one
var url = document.getElementById("iframe2").src, index = url.indexOf('#');
if(index > 0) {
var url = url.substring(0, index);
}
var newurl = url + "#" + search;
/*create a new RegExp object using search variable as a parameter,
the g option is passed in so it will find more than one occurrence of the
search parameter*/
var result = new RegExp(pagehyph, 'g');
//set the html of the iframe and add a page anchor
iframe.innerHTML = iframe.innerHTML.replace(result,"<a id='" + search + "'>" + search + "</a>" );
//set new src for the iframe with the hash
document.getElementById("iframe2").src = newurl;
};//end function
</script>
As you can see from the code, I've added a page anchor so the page scrolls to the page anchor when they click 'Go'.
function myFunction(x) {
var att = document.querySelector("iframe[id=iframe2]").getAttribute(x);
alert(att);
}
<input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" onclick="myFunction(document.querySelector('input[name=page_no]').value)" value="Go"/>
<hr />
<iframe id='iframe2' src="https://www.example.com" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe>

Why won't IE8 submit a form?

I am developing a small web application specifically for IE8 (I know you all feel the pain already). In this application, I have an Update "button" that (when clicked) generates a box where they user can click Yes or No. I used JavaScript to generate the box and the input tag with type="submit".
Here is a snippet of the code:
HTML
<form action="." method="POST" id="yield_curve_form" enctype="multipart/form-data">
<div class="fileUploadDiv">
<img id="yieldCurve" src="../img/market/yield_curve.jpg" alt="ZBPF Bond Market" >
<div class="fileUploadButton">
<span>Upload New Image</span>
<input type="file" name="image_file" accept="image/*" class="uploadInput">
</div>
<div class="fileUploadReq">
<p>Image Requirements:</p>
<ul>
<li>Format: .png, .jpg, .jpeg, .bmp, .tif, .tiff</li>
<li>Resolution: 650 x 383</li>
<li>Maximum size: 2.0 MB</li>
</ul>
</div>
</div>
<button type="button" class="marketUpdateButton" onclick="confirmUpdate('yield_curve');">Update</button>
JS
function confirmUpdate(name)
{
// Create a div element
var div = document.createElement('div');
// Give it an ID
div.id = 'preSubmitAlert';
// Create a child h2 tag
var h2 = document.createElement('h2');
h2.innerHTML = 'This is a permanent change';
// Create a child p tag
var pMessage = document.createElement('p');
pMessage.innerHTML = 'Did you double check the data? It is important the data is accurate before you submit it.';
// Create child input tags
var inputYes = document.createElement('input');
var inputNo = document.createElement('input');
// Set parameters for input tags
inputYes.type = 'submit';
inputYes.name = name + '_update';
inputYes.value = 'Yes. Update the data.';
inputYes.id = 'inputYes';
inputNo.type = 'button';
inputNo.value = 'No. Take me back, please.';
inputNo.id = 'inputNo';
// Append the children to
div.appendChild(h2);
div.appendChild(pMessage);
div.appendChild(inputYes);
div.appendChild(inputNo);
// Create the background for transparency (needed for IE8 support)
var bg_div = document.createElement('div');
bg_div.id = 'bg_div';
// Create a screen and append the above div to it
var screenDiv = document.createElement('div');
screenDiv.id = 'screenDiv';
// Appending div and bg_div to screenDiv
screenDiv.appendChild(div);
screenDiv.appendChild(bg_div);
// Appending screenDiv to the body tag
document.body.appendChild(screenDiv);
// This line needs a reference to the #screenDiv is, which is inserted in the DOM only in the above line.
inputNo.onclick = function(){destroyElement(document.getElementById('screenDiv'))};
inputYes.setAttribute('form', name + '_form');
}
Question
Why isn't the the <input type="submit" ...> not submitting the data when clicked?
Obs.: This piece of code works on every other browser, including higher versions of IE.
Thank you in advance.
Change this...
document.body.appendChild(screenDiv);
To this...
document.getElementById(name + '_form').appendChild(screenDiv);
I doubt very much that IE8 supports the HTML5 form attribute so you'll need to make the submit button a descendant of the form.
I can't find any official documentation on this though and I doubt anybody is going to the trouble of researching it properly.

Categories