Get selected text with JS - even in iFrames - javascript

Right now i get the selected text with window.getSelection().toString(). But unfortunately this doesn't work for text in iFrames. It's for a chrome extension, so i don't need to hear about how iFrames suck ;).

If you have a reference to the iframe in question then
iframeEl.contentWindow.getSelection().toString();
... will do the job. If you want to get the selected text from all iframes, you could use window.frames, which is a collection of Window objects rather than frame/iframe elements:
var selectedTexts = [];
Array.prototype.forEach.call(window.frames, function(frameWin) {
selectedTexts.push( frameWin.getSelection().toString() );
});

Related

Linking XML elements to page items in InDesign

I can check the XML of selected text like this:
app.selection[0].associatedXMLElements[0];
But in my research, I am still left scratching my head about how to do the most basic thing with XML using script: how do I assign XML to items? I can manually do this by opening the structure pane, then dragging the element over the desired frame on the page. If it's possible the old fashioned way, I imagine it's possible with script.
How do I link an existing XML element to an existing page item?
The above code only seems to work on selected text. If I select a graphic, it won't run.
How can I link XML to a selected graphic?
You can reference your xml node and your text frame and use placeXML
myXMl = myDoc.xmlElements[0];
var myXmlNode = myXMl.evaluateXPathExpression("/myXML/node1")[0];
var myFrame = app.activeDocument.pages[0].textFrames[0];
myXmlNode.placeXML(myFrame);
The advantage of this approach is that any aid:pstyle or aid:cstyle will be linked to existing matching style automaticaly
The alternative is to select the value of the node as text and place it into the text frame at insertion point:
myXMl = myDoc.xmlElements[0];
var myText = myXMl.xpath("/myXML/node1[1]/text()");
var myFrame = app.activeDocument.pages[0].textFrames[0];
myFrame.parentStory.insertionPoints[-1].contents = myText + '\r';
there are two specific properties. AssociatedXMLElement is for pageItems including textFrames and may be null if no tag is applied. AssociatedXMLElements only applies to text objects (characters, words…) because they can have several tags applied. Note that a non tagged text return an empty array and not null.
Associating tags to pageItems require that you first create or target existing xmlElements then use myInDesignObject.markup ( myXMLElement ).
EvaluateXPathExpression as Nicolai suggested is interesting once you want to browse through your XML structure. But it's sometimes quicker indeed to investigate associated XMLElement from the object rather than investigating the xml structure.
FWIW

inject into iframe from wysihtml5 text area

I've turned a simple text box into one with editing features using the wysihtml5 editor. The project necessitates that the text box inject its html into an iframe. Previous to installing the editor, things were working great. Now, the jQuery for the iframe injection no longer works, since the editor has converted the textarea to an iframe. Any ideas on how I might convert the following jQuery to work with the editor?
(function() {
var frame = $('iframe#preview'),
contents = frame.contents(),
body = contents.find('body'),
styleTag = contents
.find('head')
.append('<style>*{font-family:arial}h2{color:#CC6600}</style>')
.children('style');
$('textarea').focus(function() {
var $this = $(this);
$this.keyup(function() {
body.html( $this.val() );
});
});
})();
I know that something needs to change in the $('textarea').focus call, I just don't know what. I'm new to the javascript/jQuery world and have tried a few possibilities, but so far haven't been able to figure this one out.
Many thanks for any insight.
As i know (probably i know what im talking), you cannot apply css styling to iframes outside of iframe (from parent document). You should TRY to embed styling inside iframe. Its because browser styling works with document, but iframe its another document and must ship with own css styling. Hope this helps

Access elements in one frameset from other frameset

I have a html page in which I have two framesets each pointing to different html.
Now let's say, I have a textbox in first frameset (html) and a button in my second frameset (html).
Could anyone please let me know how to hide textbox when I click the button?
not tested, but it should be like this (in the onclick-handler of your button):
parent.frames[1].document.getElementByid('mytextfield').style.display = 'hidden';
// ^^^ here you could also access the frame by its name using ['mysecondframe']
you can do all of the above only if the two frames are in the same domain. Due to browsers security policies, if the frames aren't on the same domain and even on the same protocol, they cannot interact with each other ( javascript is out of the question ).
You can access the element via the getElementById function on the document object of the frame in question (note that we use the target frame's document, not our own). You can get the frame from the frameset by name — frame names become properties of the frameset's window object.
Example (live copy; button frame code):
var textbox = parent.targetFrame.document.getElementById('theTextBox');
textbox.value = "You clicked at " + new Date();
...where targetFrame is the name of the target frame. You can also use frames[n] where n is the index of the frame in the frameset, but I find names more robust.
The above example is tested and works on Firefox, Chrome, and Opera for Linux and IE6 — and so should work on a broad set of browsers.

JavaScript - How to get the current selection 'index' within a document

My code here returns a JavaScript selection object from within an iFrame (the iFrame page is within the same domain, so no xss issue).
What I need to know is the index of the selection within the raw html code (not the dom).
UPDATE:
E.g.
If you have an html doc:
<html><body>ABC</body></html>
And in the UI, the user uses their mouse to select the text 'ABC', I want to be able to use JavaScript to determine the postion of the selected text in the html source. In this case the index of ABC is 13.
UPDATE 2
The reason I'm persisting with this madness, is that I need to create a tool that can revisit a page and pull text based on a selected text the user has identified at an earlier time. The user tells the system where the text is, and the system from that point on uses regular expressions to pull the text. Now, if the dom is not the same as the raw html, and there's no way to pinpoint the selection in the raw html - it's really difficult to know what reg ex to generate. I don't think there's another way around this.
// Returns the raw selection object currently
// selected in the UI
function getCurrentSelection() {
var selection = null;
var iFrame = document.getElementById('uc_iFrameGetPriceData');
try {
if (window.getSelection) { // Gecko
selection = iFrame.contentWindow.getSelection();
}
else { // IE
var iframeDoc = iFrame.contentWindow.document;
if (iframeDoc.selection) {
selection = iframeDoc.selection;
}
else {
selection = iframeDoc.contentWindow.getSelection();
}
}
}
catch (err) {
alert( 'Error: getCurrentSelection() - ' + err.description )
}
return selection;
}
You can access the index and offset of your selection by using selection.anchorOffset and selection.focusOffset.
Take a look at this:
http://help.dottoro.com/ljjmnrqr.php
And here's another well explaned article:
http://www.quirksmode.org/dom/range_intro.html
update to your update: I'm not sure why you're trying to get the index of the raw HTML code. But you can walk the DOM based on the selection kinda like this:
selection.anchorNode.nodeValue.replace(selection.anchorNode.nodeValue.substring(selection.anchorOffset, selection.focusOffset), 'replace value')
Note that it's still possible that anchorOffset is before focusOffset, based on whether you selected the text from left to right or from right to left.
If I understand correctly, you're looking to move around in the DOM. In that case, you can use these methods/properties:
parentNode
getChildNodes()
firstChild and lastChild
...and these links might help:
http://www.codingforums.com/archive/index.php/t-81035.html
http://www.sitepoint.com/forums/showthread.php?t=586034
The fastest way is probably
var node = document.getElementById('myElement');
alert(node.parentNode.indexOf(node));
(Sorry, for some reason the formatting buttons aren't showing up in my "Your Answer" area...)
I would be surprised if that information was available.
No DOM API is going to let you distinguish between
<html><body>ABC</body></html>
and
<html ><body >ABC</body></html>
The index in the raw HTML is different in each case, but the constructed DOM is identical.
You can't do this sensibly: the only possible method is to re-download the page's HTML via Ajax, parse the HTML and match the resulting DOM against the current DOM, which may itself have been altered by JavaScript. Besides, it's not a useful number anyway because once the page has been loaded, the original HTML string simply no longer exists in the DOM so offsets within that string have no meaning in JavaScript. Getting the selection in terms of nodes and offsets is much more sensible.

Editing clipboard data when copying/pasting from a website

I have seen a few sites now where if you highlight text of an article, copy it, and then paste in they can add more text to it.
Try copying and pasting a section of text from an article at http://belfasttelegraph.co.uk/ and you'll see what I mean - they add a link to the original article in the pasted text.
How is this done? I'm assuming there is some javascript at work here
This is a good effect, you can see the scripting that is fired on copy using Firebug (in Firefox).
Start up Firebug and load the page, choose clear (because the page uses a lot of ajax there are very quickly 100 requests). Then choose the 'All' tab and try to copy. You will see a request for a 1x1 pixel image but if you press on the + button to look at the details, you will see in the 'params' tab that this GET request passes your requested text as the 'content' parameter, with some xpath information that will be used to manipulate the clipboard DOM:
start_node_xpath /HTML/BODY[#id='belfast']/DIV[#id='root']/DIV[#id='content']/DIV[#id='mainColumn']/DIV[#id='article']/DIV[5]/P[39]/text()
end_node_xpath /HTML/BODY[#id='belfast']/DIV[#id='root']/DIV[#id='content']/DIV[#id='mainColumn']/DIV[#id='article']/DIV[5]/P[41]/text()
As #Crimson pointed out there are methods to manipulate the clipboard, like zeroclipboard which use Flash and an image.
I reckon that is how the technique is done by using the image get request to change the clipboard.
You will notice that this happens only when you use the key combination [Ctrl+C] and not if you highlight text and chose copy from the right-click menu.
They are simply trapping the [Ctrl+C] keystroke.
Further, to add data to the clipboard, take a look at this post:
How do I copy to the clipboard in JavaScript?
I've noticed lately an influx of this "clipboard hijacking" on websites. thefutoncritic.com, cracked.com... If you use Adblock just go into the "manual entries" list and add *post-copypaste.js* to it. This should prevent the sites from adding their ads to your clipboard.
An other solution used by other websites is to use jQuery and the 'copy' / 'cut' event :
$('body').bind('copy cut',function(e){manipulate();});
Some examples here :
http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/
A news site i visit use this function to append a "source" to the copied selection:
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
// change this if you want
var pagelink = "<br><br>Fuente: Emol.com - <a href='"+document.location.href+"'>"+document.location.href+"</a><br>";
var copytext = selection + pagelink;
var newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
document.oncopy = addLink;

Categories

Resources