document.execCommand in iframe don't work - javascript

I'm working on my WYSIWYG editor. And I have code like this:
doc.execCommand(cmd, false, null);
The cmd argument would be 'Bold', 'Italic', etc. And the doc variable refer to the document in the iframe, which is initialized somewhere else:
doc = iframe1.contentWindow.document;
It works fine in Chrome, but in IE(my is IE9) doesn't work at all.
I debugged my code with the developer tool and found nothing wrong, the execCommand function just doesn't work.
I have searched through the Internet and couldn't found an available solution.
Would anyone give me a help?
Code sample:
function $see(e, o) {
var that = this;
...
this.e = $see.make('iframe', { 'class': 'editor' }); // editor iframe
this.e.onload = function () { // call when the document is loaded
var d = that.e.contentWindow || that.e.contentDocument;
if (d.document) d = d.document;
that.doc = d;
that.doc.write('<html><head></head><body></body></html>');
that.doc.body.innerHTML = that.ta.value; // that.ta refers to an textarea
that.doc.body.setAttribute('contenteditable', 'true');
...
};
}
$see.prototype.exec = function (cmd) {
// call in an <a> tag's onclick event outside the iframe
this.doc.execCommand(cmd, false, null);
};

That is because there are different methods to work with iframe in different browsers
here is how it should work
var doc= iframe1.contentWindow || iframe1.contentDocument;
if (doc.document)
doc=doc.document;
UPDATE
ok i think i made a little mistake here is how it should look like:
var doc = iframe.contentWindow || iframe.contentDocument.defaultView;
if (doc.document)
doc=doc.document;

Related

How to get Chrome to throw exception when changing url if it fails

I have a reference to a new window opened with js
var theNewTab="";
theNewTab = window.open(theURL, 'winRef');
then I change the url in the as the user clicks on another link in the parent window using
theNewTab.location.href = targetLink;
theNewTab.focus();
The problem i'm having with chrome that id doesn't throw exception if the the window doesn't exist anymore "closed" unlink FF & IE which im using to open the window again.
try {
theNewTab.location.href = targetLink;
theNewTab.focus();
}catch(err) {
theNewTab = window.open(theURL, 'winRef');
theNewTab.focus();
}
PS: I tried to use "window.open" every time but if the window already open, id does not reload the page or it does but it doesn't re-execute the script I have in document ready I think.
I'm not sure what you need.
<script type="text/javascript">
var theNewTab = null;
function openNewTab(theURL) {
if (theNewTab == null || theNewTab.closed == true) {
theNewTab = window.open(theURL);
} else {
theNewTab.location.href = theURL;
}
theNewTab.focus();
};
// use the function when you need it
$('a').click(function() {
openNewTab($(this).attr('href'));
});
</script>
Is this example helpful for you?

How to inject html into iframe, and display inside jquery-ui dialog

Here I create a jqueryui dialog from an iframe and populate the iframe with some html.
In firefox this displays nothing until I add the alert. Is there a better way to convince firefox to draw the iframe?
http://jsfiddle.net/jtmx00f4/6/
function fancyDialog(htm) {
$('<iframe></iframe>').dialog({
open: function () {
//alert('presto!');
var doc = this.contentDocument || this.contentWindow.document;
doc.body.innerHTML = htm;
}
});
}
fancyDialog('<html><body><p>Hello</p></body></html>');
While #dandavis fiddle does work in firefox, I also found a more complete solution in this article which does not require setTimeout.
http://jsfiddle.net/jtmx00f4/9/
function fancyDialog(htm) {
$('<iframe></iframe>').dialog({
open: function () {
this.contentWindow.contents = htm;
this.src = 'javascript:window["contents"]';
}
});
}
fancyDialog('<html><body><p>Hello</p></body></html>');

Ubuntu HTML5 App: Change Tab on JS command

First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!

Tab independent jQuery on Firefox extension

I'm developping a Firefox based on jQuery as described in this Answer here.
After implementing the example provided in the answer, eveything works fine, but the problem is the code between Firefox Tabs is somehow linked, and example.doc always refers to the last opened tab.
Opened tab1 : the plugin-example has been added and to the current page.
this.doc refers to tab1.
Oepened tab2: the plugin-example has been added to to current page (tab2).
this.doc now refers to tab2
back to viewing tab1 : this.doc still refers to tab1.
clicking on plugin-example on tab1 will act on the plugin-example in tab2 instead.
How can I make my code independent between tabs?
Here is an excrept from the code:
(function() {
jQuery.noConflict();
$ = function(selector,context) {
return new jQuery.fn.init(selector,context||example.doc);
};
$.fn = $.prototype = jQuery.fn;
example = new function(){};
example.run = function(doc,aEvent) {
if (doc.getElementById("plugin-example")) return;
this.doc = doc;
this.main = main = $('<div id="plugin-example">').appendTo(doc.body).html('Example Loaded!');
this.main.click(function() { //<--- added this function
example.main.html(example.doc.location.href);
});
main.css({
background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8
});
};
// Bind Plugin
var delay = function(aEvent) {
var doc = aEvent.originalTarget; setTimeout(function() {
example.run(doc,aEvent);
}, 1);
};
var load = function() {
gBrowser.addEventListener("DOMContentLoaded", delay, true);
};
window.addEventListener("pageshow", load, false);
})();
Your code (overlay script) will only run once per window, not once per tab. So there is only one example instance per window. And hence example.doc will be set to whatever dispatched DOMContentLoaded last.
Your function should properly close over the document and avoid global state.
This is who I would write it (then again, I would avoid jquery (in add-ons) like the plague...)
// Use strict mode in particular to avoid implicitly var declarations
(function() {
"use strict";
// Main runner function for each content window.
// Similar to SDK page-mod, but without the security boundaries.
function run(window, document) {
// jquery setup. per https://stackoverflow.com/a/496970/484441
$ = function(selector,context) {
return new jq.fn.init(selector,context || document);
};
$.fn = $.prototype = jq.fn;
if (document.getElementById("my-example-addon-container")) {
return;
}
let main = $('<div id="my-example-addon-container">');
main.appendTo(document.body).text('Example Loaded!');
main.click(function() { //<--- added this function
main.text(document.location.href);
});
main.css({
background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8
});
};
const log = Components.utils.reportError.bind(Components.utils);
// Do not conflict with other add-ons using jquery.
const jq = jQuery.noConflict(true);
gBrowser.addEventListener("DOMContentLoaded", function load(evt) {
try {
// Call run with this == window ;)
let doc = evt.target.ownerDocument || evt.target;
if (!doc.location.href.startsWith("http")) {
// Do not even attempt to interact with non-http(s)? sites.
return;
}
run.call(doc.defaultView, doc.defaultView, doc);
}
catch (ex) {
log(ex);
}
}, true);
})();
Here is a complete add-on as a gist. Just drop in a copy of jquery and it should be good to go.
PS: Reposted this at in the jquery in extensions question

Javascript works in FF and IE .. but Chrome says "cannot call method of null"!

The code that contains the error is:
var Slide = new Class({
initialize: function(triggers, panels) {
this.triggers = $(triggers).getElements('a[rel=content1-1]');
this.panels = $(panels).getElements('ul[class=rel-content1-1]');
this.active = -1;
this.toggle();
}, ...
})
This is called from later in the same file:
function activateSliders() {
var slide_1 = new Slide('aCol', 'content');
var slide_2 = new SlideTwo('content', 'content2', 'content2-hider');
}
window.onload = activateSliders();
Why does Chrome -- and only Chrome -- calculate $(triggers) as NULL?
In my experience, IE and FF tend to be sporadically generous with letting jQuery code work nicely without it being encapsulated within a $(document).ready( block. Try:
$(document).ready(function() {
activateSliders();
});

Categories