I've finished off a script that runs on a page that contains a textarea where an email goes.
I'm doing a variety of things on this page, however one of these is to load an iframe, based on a selected number, then once the iframe loads grab the relevant details I need from this page.
I've written the code for this inside a function called frameLoaded and I'm setting this as the onload event, yet the script still runs in to an error where it can't find the .innerHTML of an element.
If I load the iframe and then execute this script it works fine, however if I try to load the iframe and execute the script together then it runs in to this error.
Here's the code I'm using:
//Getting text currently in the textarea
var selectedTxt = document.getElementById('txtEmailText').value;
//Converting it to a string - this is just for troubleshooting purposes that I've used two variables
var insertText = selectedTxt.toString();
//Loads in the highlighted purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
//Declares global variables to hold the title and number
var purchaseTitle;
var purchaseNumber;
//Function to execute code to grab title and number once the frame has loaded
function frameLoaded() {
var iframe = document.getElementById('purchaseIframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
purchaseTitle = innerDoc.getElementById('listingTitle');
purchaseNumber = innerDoc.getElementById('auctionSoldIdDisplay');
}
//Checks to see if a purchase number has been selected
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
}
//Converting the value in the title to readable text
purchaseTitle = purchaseTitle.innerHTML;
//Placing the values in to the format I need
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
//Placing the values in to the string to go back in to the email textarea
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Am I doing something wrong here or using the wrong event as it seems to me that maybe it's trying to grab the values before the iframe has fully loaded, hence the error when I'm generating the iframe at the same time.
Please note that I cannot use JQuery
window.onload = function() is your answer.
Note in the example below, the first instance of document.getElementById('mydiv') returns null because the page (DOM) was not yet loaded and therefore neither was the div.
The second instance is fired on the windows.onload which means all the page content is present and can therefore be found.
<script type='text/javascript'>
console.log("Page not ready:" + document.getElementById('mydiv'));
window.onload = function() {
console.log("Page ready:" + document.getElementById('mydiv'));
}
</script>
<div id="mydiv">
</div>
Related
I'm trying to return the first h1 element inside an iframe I've loaded onto my page.
var res = await (await fetch(`https://www.google.com/search?q=${text}`)).text(); //Text is a variable assigned previously
var currentFrame = document.getElementById('frame0');
var currentDocument = currentFrame.contentWindow.document;
currentDocument.write(res);
var elem = currentDocument.querySelector("h1");
console.log(elem);
I'm being able to get the iframe content to show up properly but when I try to print "elem" value whenever the h1 tag of said page has a class it shows up as null.
As in:
<h1>Test</h1> //is found properly and console.log prints "Test" which is what I want
But on the other hand...
<h1 class="classyBoy">Test</h1> //isn't found properly and return null
I've tried changing querySelector("h1") to querySelector("h1 *") and querySelector("* h1") but had no success doing so.
As soon as I started waiting until currentDocument.body != null the queries started working.
I have a javascript function which is called by a 'onsubmit' within a form (Coldfusion).
<form action = "person2aa.cfm"
name = "pers2form"
method = "post"
style = "margin-left: 125px"
onsubmit = "return test()">
When the function test() is located directly below this form statement it works correctly:
<script>
function test(){
alert("got to test");
var yesa = document.getElementById('yesnoa').value;
var yesb = document.getElementById('yesnob').value;
var xx = document.getElementById('ln').value;
var x = xx.trim();
alert('supbpers2 x is ' + x);
if (x < "!"){
document.getElementById('writeval').innerHTML = "You must enter a last name.";
return false;}
else
return true;
}
</script>
(The remainder of the form continues below this script).
When I place this function anywhere else, it does not run. I have tried it in the header of the html page, and also on another page, person.js, to which the link is:
<script type = "text/javascript" src = "person.js"> </script>
The first alert 'got to test' runs in these places, but the first line starting var yesa = does not execute and the function therefore does not execute either.
The id's 'yesnoa', 'yesnob', 'ln' and 'writeval' are in the code and are correct (or the inline script would not run, but I checked anyway).
I previously had this script (minus the alerts) in the header section of my program, and it was working at one point. I have returned to retest the program some months later and the script was not functioning. I have not made any changes to this script at any time. The program itself was altered by the addition of 4 trivial queries to do various things but all look something like this:
<cfquery name = 'aa11' datasource = "Moxart">
update NameInfoDb
set perloc = <cfqueryparam value = "#perloc#">
</cfquery>
I cannot think of any connection between these additional queries and the failure of the javascript.
Can anyone explain what the problem might be? There must be an explanation, and I need to know it so I will not repeat whatever the bad code is.
I am new to javascript. I tried displaying the value of a variable on clicking a button with the following code. But it isn't working.
var i = document.getElementById("inp").value;
var m=i-1;
var s=59;
function func()
{
document.getElementById("display").innerHTML = m +":"+s;
}
In order to apply your code inside the function, you must run (call) the function:
var i = document.getElementById("inp").value;
var m=i-1;
var s=59;
function func()
{
document.getElementById("display").innerHTML = m +":"+s;
}
func();
See this JSFiddle for a live example.
At the moment your Javascript is executed the element with your id is not yet loaded because your script is located in the head.
Make sure the element you are trying to access actually exists at that moment.
Append the <script>-section at the end of your body and dont include it in the <head>.
That way the javascript runs when every element is already loaded.
I am using jQuery to GET the contents of a navigation file and load it into a div on part of my page.
I am supplying it a value containing the page name so I can update the "active" class on the navigation.
Here is the code I am using to show the GET information, this works flawlessly as when I pass it a variable from my browser (i.e header.html?page=foo) it works perfectly.
<script>
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
alert($_GET["page"]);
</script>
As you can see at the moment it just shows an alert with the value.
When I am calling this page, It is as simple as:
<script>
$("#header").load("header.html?page=bar");
</script>
For the life of me I cannot understand why it is coming back as "undefined" when called from the .load, as I have used it many times before with GET variables.
Any input would be much appreciated,
Kris.
When Javascript is being run by .load, the document is the original document, not the page being loaded.
To pass parameters to the script being loaded, use a global variable.
I am trying to copy some data from one processed web page into a new one that I want to export. The background is that I need to scrape parts of a page and need to build a new page with parts of the original page.
The problem seems that phantomJs includeJs() and evaluate() methods are sandboxed and I can't see a proper way to import DOM from one page to another.
I have some test code that looks like this, with page being the original and out the new page:
....
var title = page.evaluate(function() {
return title = document.getElementById('fooo').innerHTML;
});
console.log('page title:' + title);
//fs.write('c:/Temp/title.js', "var title = '" + title + "';", 'w');
var out = new WebPage;
out.viewportSize = page.viewportSize;
out.content = '<html><head></head><body><div id="wrapper"></div><p>done</p></body></html>';
out.includeJs('c:/Temp/title.js', function() {
var p = document.createElement('p');
p.appendChild(document.createTextNode(title));
document.getElementById('wrapper').appendChild(p);
});
...
The function in your last includeJs call here won't work - as you note, it's sandboxed, and that means that closures won't work, so title won't be defined. A method of passing variables to page.evaluate is noted as a feature request, but isn't available as of PhantomJS v.1.4.1.
The general way I get around this is by using the Function constructor, which allows you to create a function using a string:
var myVar = {some:"values", I:"want to pass into my page"},
test = new Function("window.myVar = " + JSON.stringify(myVar));
page.evaluate(test);
Now you can evaluate a function like the one you have, referencing myVar in the sandbox, and your data will be available in the client scope.