Using PHP value in javascript - working in alert() but not getelementbyid - javascript

i am using this:
$newPostID_fromCookie = $_COOKIE['scrollToBottom']+5000;
echo "
<script>
window.onload = function () {
//document.getElementById('$newPostID_fromCookie').scrollIntoView();
alert('$newPostID_fromCookie');
}
</script>
";
This correctly shows the value from the cookie in the alert, but i am getting 'is null' error when trying to use the value in the getElementById.
How can i use the value in this?

Your $newPostID_fromCookie seems to be an integer. In xHTML, this is not valid and maybe your browser does not like it. You should use a string (with a prefix for example):
document.getElementById('cookie_$newPostID_fromCookie').scrollIntoView();
Of course, change your HTML in consequence.

The getElementById() does a DOM lookup and returns the first element with the specified id.
In this case $newPostID_fromCookie should be an id of an existing element in the DOM.

Related

Rails/Rspec/Capybara: Interpreting quotes for javascript string for execute script

Given that I need to set an element's selected index with javascript in capybara by the input name...
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
What is the proper way to interpret this as a string so it can be executed in Capybara with execute_script(function_name_string)? Because I keep getting syntax errors, unsure how to nest the " and ' quotations.
Easiest solution to your question is to use a heredoc
page.execute_script <<~JS
var element = document.querySelector("select[name='user[user_locations_attributes][0][location_attributes][state]']").selectedIndex = '50';
JS
Although if you have need for the element for anything else it's probably nicer to find the element in ruby and then just call execute_script on the element
el = find("select[name='user[user_locations_attributes][0][location_attributes][state]']")
el.execute_script('this.selectedIndex = 50;')
As a related question - is there a reason you're doing this via JS rather than just clicking on the correct option? If you're just scraping a page there's no issue, but if you're actually testing something this basically makes your test invalid since you could potentially be doing things a user couldn't
Since you commented that you are testing, you really shouldn't be doing this via JS, but should instead be using select or select_option. select takes the options string (which you should have - otherwise why have a select element in the first place)
select('the text of option', from: 'user[user_locations_attributes][0][location_attributes][state]')
select_option is called on the option element directly, which can be found in a number of ways, such as
find("select[name='user[user_locations_attributes][0][location_attributes][state]'] option:nth-child(50)").select_option

Selenium read text of hidden web element using Xpath

I'm facing an issue in one of our automated script wherein I need to read the text of an element whose accessibility is hidden, since selenium can't read text of hidden elements. I checked other posts here as well and they suggest to execute javascript and read innerHTML using the element's ID. In our case the challenge is I can't use ID of the web element as its dynamic and changes each the time the page is loaded in web browser so I'm bound to rely on Xpath's, please find below the code of the element -
<div id="milestone_gwt-uid-2132" class="accessibilityhidden">Current Step: Referral Details</div>
Now id i.e. "milestone_gwt-uid-2132" is not static and changes whenever the page is loaded and I want to read the text - "Current Step: Referral Details". Is there any effective way to do that using Selenium Java?
Thanks
The method getText returns the visible text. Use executeScript to get the hidden text:
WebElement elem = driver.findElement(By.xpath("//div[contains(text(), 'Current Step:')]"));
String hiddenText = (String)((JavascriptExecutor)driver).executeScript(
"return arguments[0].textContent;", elem);
Note that assessing some hidden text in a test is probably a bad idea since it doesn't reflect what the user can see.
You can use dynamic id in your XPath in following way:
//div[contains(#id, "milestone_gwt-uid-")]
You can get innerHTML with following code
WebElement element = driver.findElement(By.xpath('//div[contains(#id, "milestone_gwt-uid-")]'));
String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
Thanks! Works with MS Word Online!!
calling the method:
String textFromEditor = getValue(driver.findElement(By.id(editorFieldId)));
the body of method:
protected String getValue(WebElement element) {
try
{
String value = (String)((JavascriptExecutor) driver).executeScript("return arguments[0].textContent;", element);
return value;
}
catch (Exception e)
{
return "can't get text";
}
}
You can assert the element by concatenating two Texts since the DOM will always contain a unique element.

jQuery Fallback to Creating DOM Object If Search Is Empty?

I just found a weird case that resulted in XSS, but I don't really understand why. The code in question was searching for a tag with a matching name like this:
var varName = getCookie('cookiename');
var link = $('.someclass a[name=' + varName + ']');
If that cookie happens to contain XSS, executing that jQuery code results in the XSS being executed. I understand that on its own, something like $('< img src=x onerror=alert(1) />') will be added to the DOM and executed, based on what I read in the documentation. I don't get why the code above, with that same img tag as the variable value, has the same result. Shouldn't it just result in an empty variable?
In older versions of jQuery, the following jquery selector would result in a div being created:
$('.someclass a[name=' + '<div>Hello World!</div>' + ']')
however, in more recent versions of jQuery, jQuery will not create a dom fragment unless the html string starts with a < which completely avoids this issue.
So, either validate the input before putting it in the selector, or update jQuery.
http://jsfiddle.net/g33n57vs/

Nothing for innerHTML of div

I am trying to use javascript to grab the innerHTML of an element. The innerHTML is the results of a query ran. Sometimes the query returns no data so there is nothing inside of the div. I do an alert and it says '[object HTMLDivElement]'. I need to account for this when there is no data for the innerHTML in an if statement. Does anyone know how I would do this? How would I write the IF part?
var HSA_EmployeeCont = document.getElementById('HSA_EmployeeCont').innerHTML;
//alert(HSA_EmployeeCont);
if (HSA_EmployeeCont == 'object HTMLDivElement') {
...
Check the length of the innerHTML:
if (!HSA_EmployeeCont.length)
console.log("Nothing here!");
if (!HSA_EmployeeCont) should do the trick.
Your alert should be showing nothing, perhaps you forgot to add innerHTML before you tested with an alert?

How to store html in hidden field using jquery?

How to store string with HTML tags in hidden field using jquery?
I am using the below code. But its not working.
var terms = $('#TermsAndCondition').val();
alert($('#hdnTerms').val(terms));
Here TermsAndCondition is TextArea and hdnTerms is hidden field.
In alert it returns the object.
use something like this
var value=$("input[type=hidden]").val();
alert(value);
You're just querying it wrong, try this
var terms = $('#TermsAndCondition').val();
alert($('#hdnTerms').val(terms).val()); //Note the extra .val() so you get the value
.val(terms) returns a jQuery object, not the value, you need to call .val() with no parameters to get a the value returned.
Assigning to .val() does not return the text (it returns a jQuery object), change your test to:
$('#hdnTerms').val(terms);
alert($('#hdnTerms').val());
To access the value you must call val() without parameters.
May I suggest you to simply use:
//hide terms when you don't need them
$("#TermsAndCondition").hide();
//show them again when you want
$("#TermsAndCondition").show();
not sure what you are trying to achieve there

Categories