firefox web extension tutorial: script repeat itself - firefox

I've followed the following guide to train myself at firefox addon:
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
Then I started tweaking the code to add my own functions, keeping the same architecture/logic.
But then I noticed that my functions, when launched by clicking in the menu, execute sereval times, actually the number of times I've clicked in the addon menu since I loaded the page.
example: I created a menu option called Repeat Test that links to a function called "Repeat Test" that is just console.log('1');
- first click, I get 1
- second click, I get 1 / 1
- third click, I get 1 / 1 / 1
where can that come from ?
my code:
beast.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="choose_beast.css"/>
</head>
<body>
<div class="beast">Remove Model Map</div>
<div class="beast">Color Formulas</div>
<div class="beast">Image Overlay</div>
<div class="beast">Repeat Test</div>
<script src="choose_beast.js"></script>
</body>
</html>
choose_beast.js:
function optionSelection(myvar) {
switch (myvar) {
case "Remove Model Map":
return "modelMap";
case "Color Formulas":
return "colorFormulas";
case "Image Overlay":
return "imageOverlay";
case "Repeat Test":
return "repeatTest";
}
}
document.addEventListener("click", function(e) {
if (!e.target.classList.contains("beast")) {
return;
}
var clickedOption = e.target.textContent;
var optionActivated = optionSelection(clickedOption);
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {option: optionActivated});
});
});
and finally, beastify.js:
function myaddon(request, sender, sendResponse) {
switch (request.option){
case "modelMap": removeModelMap();
case "colorFormulas" : colorFormulas();
case "imageOverlay" : overlay();
case "repeatTest" : repeatTest();
}
}
function repeatTest()
{
console.log('1');
}
chrome.runtime.onMessage.addListener(myaddon);

I've found the issue here. this code
chrome.tabs.executeScript(null, {
file: "/content_scripts/beastify.js"
});
is contained into the click event manager, so every time you click, the script is executed, which adds to the fact that later on a message is sent to the script every time a click is made.
I don't know if this is a mistake or not (it's actually like this on the mozilla website):
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension
but it was quite annoying for me. I'll notify them.

Related

Line spacing in CKeditor

apologies but I am an absolute noob on this. I have implemented a CKeditor on my website using the below HTML:
<!doctype html>
<html>
<head>
<!--Define the character set for the HTML element -->
<meta charset="utf-8">
<!--Call the external script to use the CDN CKEditor in your page-->
<script src="//cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
<script type="text/javascript">
//Define an init function that sends the rich text editor contents to the page code
function init() {
//onMessage runs when the HTML element receives a message from the page code
window.onmessage = (event) => {
if (event.data == "x") {
CKEDITOR.instances.CK1.setData( '<p></p>' );
console.log(event.data,"ok");
} else {
//postMessage sends the contents of the CKEDITOR back to the page code
window.parent.postMessage(CKEDITOR.instances.CK1.getData(),"*");
console.log(event.data,"okd");
}
}
}
</script>
</head>
<body onload="init();">
<!--Define the HTML element as a textarea-->
<textarea name="editor1" id="CK1"></textarea>
<script>
//Use the CKEditor replace() function to turn our textarea into a CKEditor rich text editor
CKEDITOR.replace("editor1");
</script>
</body>
</html>
It works great but I have a line spacing issue where it looks like there is a line in between the paragraphs, but when it displays later on it is on top of each other. Is there anyway to reduce the spacing so the user realises they need to press enter again?
Image attached, first test is 1 press of enter after text (which looks like it has a line between but doesn't), second is 2 enters.
My issue is also that I am using Wix, so I can't host the config or whatever files to change. So it all needs to be from the html link.....
Thanks!
enter image description here
These lines of code will remove extra space
:host ::ng-deep .ck-editor__editable_inline p {
margin: 0;
}
Do you need to force the user to press Enter twice for a new paragraph? If so, try this:
CKEDITOR.addCss('.cke_editable p { margin: 0 !important; }');
CKEDITOR.replace('editor1');

Google App Script and Html Form not communicating

I need help with Google App Script on a Google Sheet and an Html form. I just cannot get them to connect properly. The form has a text box and two buttons. The user enters a name in the text box and press the start button. The start button records time to a variable. When finished, the user presses finish. The finish button records the time and processes the text box and start button. This info is sent back to the Google App Script to be written to the Sheet. I would like to use an AJAX or JQuery call, but it doesn't seem to be working. Need a little help getting the nice form working. I have tried doGet(e) and doGet() functions, but those aren't working. I have tried lots of different versions of the code. This isn't my final html form, but it has the same point. If I click the button, AJAX should return something to the Google App Script after processing. New to Google App Scripting and need help. Thanks!
code.gs
function doGet(e) {
var result = "";
try {
result = "Hi" + e.queryString;
//should write to the spreadsheet the information here
} catch (f) {
result= "Error" + f.toString();
}
result=JSON.stringify({"result":result});
return ContentService
.createTextOutput( "(" + result + ")")
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
//where does HtmlService.createHtmlOutput('index.html') go?
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Make an AJAX call to Google Script
function callGoogleScript() {
var url = "https://script.google.com/macros/s/" my script id "/exec";
var data = { name: "Tom", city: "Nowhere" };
var request = jQuery.ajax({
url:url+encodeURIComponent(data),
method: "GET",
dataType: "jsonp"
});
}
// print the returned data
function ctrlq(e) {
console.log(e.result)
}
</script>
</head>
<body>
<button id="test" name="test" onclick="callGoogleScript()">Test</script>
</body>
</html>
Edit: This is for a Web App.

CKEditor4 Clipboard issue

I am trying to select all the content from a CKEditor instance and copy it to the clipboard when the user clicks a button on a different part of the screen. When the page initially loads, and I click the "Copy to Clipboard" button, the selectAll command works, but the copy command does not work. However, if I click the button a second time, everything works correctly.
Does anyone know how to resolve this issue? I am new to CKEditor, but this seems like a focus or timing issue. I'd rather not have to code phantom button clicks to make this work. Any help is greatly appreciated.
Here is my code. As you can see, I also tried wrapping the copy command in the "afterCommandExec" callback from the "selectAll" command. That didn't work either.
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
var g_editorObj = new Object;
window.onload = function () {
g_editorObj = CKEDITOR.replace('editor1');
}
function doCopyClipBoard() {
try {
g_editorObj.focus();
g_editorObj.execCommand("selectAll");
g_editorObj.execCommand("copy");
//g_editorObj.on('afterCommandExec', handleCopy);
} catch (ex) {
alert(ex.Message);
}
}
function handleCopy() {
g_editorObj.execCommand("copy");
}
</script>
</head>
<body>
<input type="button" onclick="doCopyClipBoard()" value="Copy to Clipboard" /><br />
<textarea id="editor1" name="editor1" rows="10" cols="80">Testing this thing</textarea>
</body>
</html>
Please check if this order of things will work for you:
editor.focus();
editor.once( 'selectionChange', function() {
editor.execCommand( 'copy' );
} );
editor.execCommand( 'selectAll' );
or alternatively:
editor.execCommand( 'selectAll' );
setTimeout( function() {
editor.execCommand( 'copy' );
}, 0 );
Note that access to the clipboard is only possible in IEs. It's a matter browser limitations and there's no way to bypass that thing.

Problems with mouse events on newly created CKEditor instance

I'm trying to create a create a new CKEditor ver4 instance in response to the user clicking on an element. Due to the nature of the application, I can not use the "autoInline" feature as outlined in the CKEditor Sample. While the sample below does in fact create an editor instance, that instance has a significant problem. Inline instances are supposed to disappear when the user clicks away from them. In this example however, the user must first click away, click back into the instance, and then click away again. How can I prevent this?
<!doctype html>
<html>
<head>
<script src="jspath/ckeditor.js"></script>
<script>
var editor = null;
CKEDITOR.disableAutoInline = true;
function init() {
var e2 = document.getElementById("element2");
e2.addEventListener("click", function () {
if(!editor) {
editor = CKEDITOR.inline(e2);
editor.on('instanceReady', function () {
console.log("instanceReady")
console.log(editor.focusManager.hasFocus);
});
editor.on('focus', function() {
console.log("focus");
})
editor.on('blur', function() {
console.log("blur");
editor.destroy();
editor = null;
})
}
})
}
</script>
</head>
<body onload="init()">
<div tabindex="0" id="element2" style="background-color: yellow;" contentEditable = true>Element 2</div>
</body>
</html>
Despite the fact that editor.focusManager.hasFocus was true, the editor's element did not in fact have focus. Perhaps this is a bug? Anyway, adding editor.focus(); to the instanceReady function resolved the issue.

Pop up window self close function; close the site as well

I have an Ajax call back function which call to a PHP function check the file modified time.
I uses timer to execute it every 50 seconds.
<script type="text/javascript">
setInterval("_checkPopUpUpdate()", 50000); //50 seconds
</script>
function _checkPopUpUpdate()
{
var callback=new Object();
callback.success=this.onExternalSuccess;
callback.failure=this.onExternalFailure;
YAHOO.util.Connect.asyncRequest('GET','/ci/ajaxCustom/ajaxCheckPopupUpdate',callback);
};
The PHP function checks whether the file modified time has different between the first load session time
$announcement_Popup_Path = HTMLROOT . $this->data['attrs']['file_path'];
// Call model function
if($this->data['attrs']['file_path'] !== '' && file_exists($announcement_Popup_Path))
{
//When the announcement content load, it always stores the modified time into session
$this->CI->load->model('custom/checkupdate_model');
$firstloadTime = filemtime($announcement_Popup_Path);
$this->CI->checkupdate_model->store_AnnouncementPopupSession($firstloadTime);
//$this->data['Popup'] = file_get_contents($announcement_Popup_Path);
}
function store_AnnouncementPopupSession ($popupTime)
{
$sessionPopupTime =array("annoucementPopUp"=> $popupTime);
$this->session->setSessionData($sessionPopupTime);
}
function announcement_pop()
{
$file_path='/euf/assets/announcements/pop_up_announcement.html';
$announcement_Popup_Path = HTMLROOT . $file_path;
if(file_exists($announcement_Popup_Path)) {
$currentAnnouncementPopUpTime = filemtime($announcement_Popup_Path);
$oldannouncementPopupTime = $this->session->getSessionData("annoucementPopUp");
if($currentAnnouncementPopUpTime !=$oldannouncementPopupTime) {
//comparing the content and update the time, when they are different, send back update content
$this->store_AnnouncementPopupSession($currentAnnouncementPopUpTime);
//echo $currentAnnouncementPopUpTime;
echo $file_path;
}
else {
echo "no update";
}
}
}
When the file modifed time has changed, it will return to ajax call back and grab the HTML content in my web server to Pop up an annoucement pop up window.
function onExternalSuccess (o){
if(o.responseText!==undefined)
{
var str=o.responseText;
if(str !== 'no update') // Then pop up.
{
L=screen.width-200;
T=screen.height;
popup=window.open(str," ",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=150,width=364,left="+L+",top="+T');
//popup=window.open(str,"",'alwaysRaised=yes,status=no,toolbar=no,location=no,menubar=no,directories=no,resizable=no,scrollbars=no,height=100,width=330');
for (i=0;i<200;i++)
{
T=T-1;
popup.moveTo(L,T);
}
}
}
};
It works fine for Firefox and Chrome, however IE7 is a bit bugy, sometime the pop up does not come out.
<html>
<head>
<title>Internal alert</title>
<link rel="stylesheet" type="text/css" href="/euf/assets/css/pop_up_ann.css" media="screen, projection" />
<script type="text/javascript">
var howLong = 50000; //5 minutes, 1 seconds = 1000 milliseconds.
t = null;
function closeMe(){
t = setTimeout("self.close()",howLong);
}
</script>
</head>
<body onLoad="closeMe();self.focus();">
<div id="cs_popup">
<div class="popup_rounded-corner-top">
<div id="popup_ann">
<div id="popup_ann_title">IE7 pop-up EMEA test close </div>
<div id="popup_ann_from"> PLC team - 05/01/2011 at 12:10</div>
<div id="popup_ann_content">
Something has changed in the<em>"Alerts"</em> section of S4S since your last visit.
Make sure you go there as soon as you can to be informed about the current situation.
</div>
</div>
</div>
<div class="popup_rounded-corner-bottom"></div>
</div>
</body>
</html>
The main problem i have here it is self-close function. It close my pop up window and the website as well. Any hints? Also, i am not sure whether my whole pop up annoucement logical structure is correct, is there anyway? thanks
Opening a popup window for an announcement like this could be problematic for people running popup blockers, which typically only allow popups to appear in response to a user-initiated event like clicking on something. A better approach would be to use an inline popup which would also give you the opportunity to display the popup modally (i.e. mask the rest of the page with a semi-transparent div) if you require them to acknowledge your message.
The use of self.close() should not close the original window/tab opened by the user, it should only close things that have been 'open'ed so I'm not sure what's going on there, I suspect you haven't told us everything :) An alternate approach might be to modify your popup function to close the window rather than have the window close itself.
// open popup ... then set timeout to close it
var popupDelay = 50000;
setTimeout(function() {
popup.close();
}, popupDelay);
This may work a little better, not sure. But in the long run, I highly recommend avoiding popups and using something inline instead.

Resources