Writing to Tinymce with Webdriver and Ruby - ruby

Maybe I'm just missing something but I'm trying to use webdriver and Ruby to enter text into a WYSIWYG. I don't receive any errors but text does not get entered as well.
Here is my code that I wrote
tinymce_frame = driver.find_element(:id => "Speakers_ifr")
driver.switch_to.frame(tinymce_frame)
editor_body = driver.find_element(:css => 'body')
#I also tried replacing 'body' with the line of code below
#editor_body = driver.find_element(:css => "html body#tinymce.mceContentBody")
editor_body.send_keys("BOB")
Here is the HTML from Firebug
<iframe id="Speakers_ifr" frameborder="0" src="javascript:""" allowtransparency="true" title="Rich Text AreaPress ALT-F10 for toolbar. Press ALT-0 for help" style="width: 100%; height: 256px; display: block;">
<!DOCTYPE >
<html>
<head xmlns="http://www.w3.org/1999/xhtml">
<body id="tinymce" class="mceContentBody " contenteditable="true" onload="window.parent.tinyMCE.get('Speakers').onLoad.dispatch();" spellcheck="false" dir="ltr">
<br data-mce-bogus="1">
</body>
Thanks for any suggestions.
Scott

I just needed to add a couple of lines of code.
tinymce_frame = driver.find_element(:id => "Speakers_ifr")
driver.switch_to.default_content # Added this line
driver.switch_to.frame(tinymce_frame)
editor_body = driver.find_element(:tag_name => 'body')
driver.execute_script("arguments[0].innerHTML = 'bob'", editor_body) #Added this line
My next challenge is trying to make 'bob' a variable that is being passed into the function. I'll write that up as another question, if I cannot find it.

Related

React-Quill does not preserve HTML response and dictates its own tags - Messes up the layout

EDIT: We replaced Quill with TinyMCE and solved all our issues. We can successfully insert HTML response (as is) into tinyMCE's state as well as modify it!
We're experiencing a styling issue. We're building a mail templating
application and the user can create/modify their templates. We also provide preexisting templates for our users.
The issue we're experiencing is the following.
1- We send the user a mail template. The initial/original response sent to the user is the following HTML
<html>
<head>
<title>FINROTA</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
</head>
<body bgcolor=\"#FFFFFF\" leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" style=\"font-family: Verdana, Geneva, Tahoma, sans-serif\">
<table width=\"670\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\">
<tr>
<td bgcolor=\"#FFFFFF\">
<table bgcolor=\"#FFFFFF\" width=\"575\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">
<!-- Header -->
<tr>
<td bgcolor=\"#FFFFFF\">
<table width=\"575\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-bottom: 1px solid #F3F3F3;\">
<tr>
<td style=\"height: 94px;text-align: center;\">
<a href=\"https://portal.finrota.com/\">
<img width=\"120\" height=\"30\" style=\" display: initial;padding-top: 20px;\" src=\"https://cdnecozum.com/static/images/mailing/header.png\" alt=\"finrota-logo\" />
</a>
</td>
</tr>
</table>
</td>
</tr>
<!-- /Header -->
</table>
</td>
</tr>
</table>
</body>
</html>
2- We then take this html response and set the react-quill 'state' with it
import { textEditorOptions } from "lib/constants";
import React, { forwardRef, useImperativeHandle, useRef } from "react";
import ReactQuill from "react-quill";
const editorOptions = {
toolbar: false,
clipboard: {
matchVisual: false
}
},
TemplateEditor = forwardRef(({ formParamForQuill, setFormParamForQuill, shouldHideToolbar, data, stateData, update, communicationType }, ref) => {
const [quillState, setQuillState] = React.useState({ description: data || "" }),
editorRef = useRef(),
handleQuillChange = val => {
setQuillState(() => ({ description: val }));
update(`${communicationType}`, { ...stateData[`${communicationType}`], body: val });
};
useImperativeHandle(ref, () => ({ editorRef }));
React.useEffect(() => {
if (formParamForQuill.token !== null && formParamForQuill.explanation !== null)
setFormParamForQuill({ token: null, explanation: null, ref: null });
}, [formParamForQuill]);
return (
<>
<div className="communication-template-quill">
<ReactQuill
ref={editorRef}
modules={!shouldHideToolbar ? textEditorOptions : editorOptions}
value={typeof quillState.description === "string" ? quillState.description : quillState.description.join("")}
onChange={value => handleQuillChange(value)}
/>
</div>
</>
);
});
export default TemplateEditor;
'data' passed onto the editor component as a prop is the initial HTML response attached above. However, when the quill state is set with this 'data', quill state then becomes this (state modified by react-quill (attached below)), which does not preserve the original HTML thus leaving us with a messed up layout.
<p>FINROTA <a href=\"https://**.**.com/\" rel=\"noopener noreferrer\" target=\"_blank\">
<img src=\"https://*****.com/-/-/-/-.png\" alt=\"finrota-logo\" height=\"30\" width=\"120\">
</a>
<img src=\"https://*****.com/static/images/mailing/pay.png\" alt=\"top-images\" height=\"128\" width=\"123\"> Sayın <strong style=\"color: rgb(16, 16, 16);\">{{-}},</strong>
</p>
<p>---</p>
<p>---</p>
<p>
<strong>** ** **</strong> Sistem Destek E-Mail: <strong> **#**.com </strong> Telefon: <strong> 0(**) ** ** 00 </strong> Fax: <strong> 0(**) ** ** 00 </strong>
<a href=\"https://twitter.com/*****\" rel=\"noopener noreferrer\" target=\"_blank\">
<img src=\"https://******.com/static/images/mailing/twitter.png\" alt=\"twitter\" height=\"32\" width=\"32\">
</a>
<a href=\"https://www.linkedin.com/company/*****/mycompany/\" rel=\"noopener noreferrer\" target=\"_blank\">
<img src=\"https://*****.com/static/images/mailing/linkedin.png\" alt=\"linkedin\" height=\"32\" width=\"32\">
</a>
<a href=\"https://www.facebook.com/*****/\" rel=\"noopener noreferrer\" target=\"_blank\">
<img src=\"https://*****.com/static/images/mailing/facebook.png\" alt=\"facebook\" height=\"32\" width=\"32\">
</a>
<a href=\"https://www.instagram.com/EcozumAS/\" rel=\"noopener noreferrer\" target=\"_blank\">
<img src=\"https://*****.com/static/images/mailing/instagram.png\" alt=\"instagram\" height=\"32\" width=\"32\">
</a>
</p>
How could the original HTML be preserved ? How do we overcome this styling issue ?
Short answer
No, you can't just throw any markup into a WYSIWYG editor and expect it to be able to perfectly work with the structure. These editors work with a subset of HTML.
Emails usually use ancient styling techniques. Even if Quill is able to correctly parse each tag and attribute, the result would likely be terrible to work with while editing. Emails often put everything in a table and need to add inline styles to work in older clients.
You can get part of the way there by only injecting the actual visible body content into Quill, not an entire HTML document.
The document head is not something that you could edit in a WYSIWYG editor. As you can see Quill just removes all tags it doesn't "know about" from around the content. Then it adds p tags around orphaned text. Hence you see the document title in the output as a paragraph.
1- We send the user a mail template
You only need to send the user the part of the template they can edit. The outer HTML is something that can be added by your server when the mail is finally sent.
The second problem is that the email content seems to be from a pre-existing application that formatted everything as tables. Also it contains a bunch of inline styles.
Quill is not a sophisticated HTML parser. (I mean, come on, it doesn't even remove the head tag) Neither is it very good at outputting HTML.
So if you want to convert this text to an email with that specific mark up, you'll have to do this conversion yourself from the tags and style attributes returned by Quill's content.
You'll probably also have to do a one time effort to convert these old templates into a format Quill can work with. Or write a function that can convert between the formats.
You could also try quil-better-table. It might improve Quill's ability to pick up table markup in the input.
If you're sending your emails with PHP, you could try quil-delta-parser or php-quil-renderer.
That way you can send Quill's "deltas" to your back end, and transform them to the right HTML at save time, or even when the email is sent.
You can install both with Composer.
composer require nadar/quill-delta-parser
or
composer require deanblackborough/php-quill-renderer
Both libraries seem flexible enough to make it output the styles you want based on which attributes are in Quill's delta.
In any case it's probably very challenging if not impossible to make Quill understand and return the exact same markup of the template you post. Much easier to just take whatever it outputs and transform it afterwards.

Cannot locate link css or xpath

I started to learn ruby (rspec , rubymine).
I want to do simple click action but I have a problem.
Id and name does not exist so, I should use xpath or css.
I tried #click on contact link:
driver.find_element(:css, 'html>body>footer>div>div>section:nth-child(3)>a:nth-child(1)').click + ' :: absolute path'
xpath showed me:
/x:html/x:body/x:footer/x:div/x:div/x:section[3]/x:a[1]
link is:
Contact
and this is FIRST link in:
section class="link-block link-collection col-xs-12 col-sm-4 col-md-2"
and section class is placed in div: class="row"
and this is here: <footer class="footer" role="info">
and this is inside: <body data-touch="false" class="abc">
Can anybody help me?
I used now Css but...it clicks on another links and css is the same! strange..hm
css: .footer .container .row .link-block h4 + a
so, how can I do this with xpath?;/
I used
#driver.find_element(:xpath, '//html/body/footer/div/div/section[3]/a[1]').click and it works:) but..what if sth will be changed on page?

Optimize website to show reader view in Firefox

Firefox 38.0.5 added a "Reader View" to the address bar:
But not all sites get this icon, It only appears when readable content page is detected. So how do I enable this for my site?
I tried media print and an extra stylesheet for print-view, but that has no effect:
<html>
<head>
<style>
#media print { /* no effect: */
.no-print { display:none; }
}
</style>
<!-- no effect either:
<link rel="stylesheet" href="print.css" media="print"><!-- -->
</head><body>
<h1>Some Title</h1>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+should+vanish+in+print+view">
<br><br><br>This is the only text
</body></html>
What code snippets do I have to add into my website sourcecode so this book icon will become visible to the visitors of my site?
As the code stands in May '20 the trigger function (isProbablyReaderable) scores only p or pre elements and div elements that contain at least one decedent br.
A slight oversimplification of the scoring heuristic is:
For each element in ['p', 'pre', 'div > br']:
If textContent length is > 140 chars, increase score by sqrt(length - 140)
if cumulative score > 20, return true
You have to add <div> or <p> tags to achieve a page to iniciate the ReaderView.
I created a simple html that works:
<html>
<head>
<title>Reader View shows only the browser in reader view</title>
</head>
<body>
Everything outside the main div tag vanishes in Reader View<br>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+should+vanish+in+print+view">
<div>
<h1>H1 tags outside ot a p tag are hidden in reader view</h1>
<img class="no-print" src="http://dummyimage.com/1024x100/000/ffffff&text=This+banner+is resized+in+print+view">
<p>
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
123456789 123456
</p>
</div>
</body>
</html>
This is the minimum needed to activate it. This is a somewhat multi-faceted process where scores are added for text chunks.
You can for example activate the reader view in forum's software if you add a <p>-tag around each message block in the view-posts template.
Here are some more details about the mechanism

How to perform Ctrl+multiple mouse clicks operation using Ruby with Selenium Watir-webdriver?

I came across a difficulty where I have to perform Ctrl+mouse click operation using watir-webdriver with Ruby
In my web application application I have to select multiple options using Ctrl key plus mouse clicks (random options not all options). I could see multiple solutions using C# or Java. But I couldn't find any solution using Ruby and Watir-webdriver. Can anyone help me?
I have tried using the below code
regionsArray=['Airlines', 'Biotechnology', 'Financial Conglomerates', 'Food Retail', 'Restaurants', 'Savings Banks and Tobacco']
oPage.action.key_down(:control)
puts "hello2"
regionsArray.each { |x|
indXpath="//div[#id=('options-tree-region')]//div[text()='#{x}']"
indText = UtilsCommon.GetElementWithXpath(oPage, indXpath, 10, true)
if indText!= false
indText.click
end
I assume that the control behaves similar to the jQuery UI selectable and will use their demo as an example.
The demo page is:
<html lang="en">
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<style>
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>
<script>
$(function() {
$( "#selectable" ).selectable();
});
</script>
</head>
<body>
<ol class="ui-selectable" id="selectable">
<li class="ui-widget-content ui-selectee">Item 1</li>
<li class="ui-widget-content ui-selectee">Item 2</li>
<li class="ui-widget-content ui-selectee">Item 3</li>
<li class="ui-widget-content ui-selectee">Item 4</li>
<li class="ui-widget-content ui-selectee">Item 5</li>
<li class="ui-widget-content ui-selectee">Item 6</li>
<li class="ui-widget-content ui-selectee">Item 7</li>
</ol>
</body>
</html>
Option 1 - Using ActionBuilder
As you noticed, you could call down to the Selenium-WebDriver ActionBuilder to press control and then click the elements. I am guessing that your code did not work was because the perform method was never called for the action. For the demo page, to hold control and click each li would be:
# Press control (note the call to 'perform' the action)
browser.driver.action.key_down(:control).perform
# Click the elements
browser.lis.each(&:click)
So that control is pressed and then released at the end, you could also do:
action = browser.driver.action
action.key_down(:control)
browser.lis.each { |li| action.click(li.wd) }
action.key_up(:control)
action.perform
Option 2 - Using Modifiers for Click
An alternative solution would be to use Watir's click method with modifiers. The modifiers can be used to tell Watir to hold down certain keys while clicking an element. For example, the following will press control while clicking each li:
browser.lis.each do |li|
li.click(:control)
end
Note that this is technically a different user behaviour than that in Option 1. In Option 1, the control button is held while all lis were clicked. In contrast Option 2 will press the control button, click the element, release the control button and then repeat for the next element. Depending on the application's implementation, it may or may not care about the difference.

IE8 fbml like button and eot (font embedding)

I have issue with one of site that I developing.
Situation is like this:
I'm using #font-face generated at fontsquirrel.com, and in every browser, except for IE8 it works fine. In the beginning it worked for IE8 too, but (I guess) after update it stops working normally.
This is what's happening, after page is loaded, font on the page stays the same until you mouse over the document, after that it applies #font-face rule.
You can see that here: http://devel.2klika.net/fiolic/demo/home.php
Also I'm using fbml on that page for fb:like button, this is the code:
<span style="float: right; position: relative; left: 10px;">
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:like href="http://www.facebook.com/#!/pages/Mesnice-Fiolic/174173775933578" layout="button_count" show_faces="false" width="50" font="arial"></fb:like>
</span>
I figured that commenting out fb:like is solving, sort of, #font-face problem, like this:
<span style="float: right; position: relative; left: 10px;">
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<!-- <fb:like href="http://www.facebook.com/#!/pages/Mesnice-Fiolic/174173775933578" layout="button_count" show_faces="false" width="50" font="arial"> </fb:like> -->
</span>
I would like to use that fb:like button if it is possible to make it work with IE8 and #font-face :)
I tested this with Windows 7 64bit, IE 8.0.7601.17514 64bit and 32bit
If I'm using IE8 in compatibility view it works normally.
Does anyone can help me with this issue?
Thanks in advance
I had found a lot of responses on other forums talking about adding namespaces to the html tag as a way of making this work. I decided to try it my self and with great joy, the like button was displaying in IE8.
I changed my html tag from:
<html>
to:
<html xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/">
As seen in the code I used below:
<html xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/">
<head>
</head>
<body>
<div><fb:like id="fb_like_btn_iframe" show_faces="no" width="220" href="http://www.pixorial.com"></fb:like></div>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
api_key = "<%= FACEBOOK['key'] %>";
FB.init({
appId : api_key,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
var like_clicked = function(href, widget){
$.ajax({
type : "POST",
url : '<%= url_for :controller => :gallery, :action => :update_likes %>',
data : {"url_of_like": href, "type": "like", "authenticity_token": <%= form_authenticity_token.inspect %>}
});
parent.likeButtonChanged(href);
}
var like_unclicked = function(href, widget){
$.ajax({
type : "POST",
url : '<%= url_for :controller => :gallery, :action => :update_likes %>',
data : {"url_of_like": href, "type": "unlike", "authenticity_token": <%= form_authenticity_token.inspect %>}
});
parent.likeButtonChanged(href);
}
$(document).ready(function(){
FB.Event.subscribe('edge.create', like_clicked);
FB.Event.subscribe('edge.remove', like_unclicked);
})
</script>
</body>
</html>
I have encountered the same issue. Quite frustrating as there doesn't seem to be a solution aside from removing the like button from the page.
I've submitted a bug report to facebook for this issue.

Resources