Word Office online insert/edit text using browser extension - javascript

I'm developing a chrome extension which can insert/edit paragraph on World Office web/browser version that use onedrive as the text editor platform, at first I'm inserting the text via simple HTML DOM to inserting a text but it will not saved or disappeared if we click on the text editor. Is there any way to correctly insert or edit a text on Word Office web ?
here's the code that I've tried:
content_script.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
var node = document.querySelectorAll(".OutlineElement");
var clone = node[node.length-1].cloneNode(true);
document.getElementsByClassName("OutlineGroup")[0].appendChild(clone);
console.log(window.getSelection());
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
popup.js:
chrome.tabs.query({active:true, lastFocusedWindow: true},
function(tabs) {
console.log(document.querySelectorAll('li'))
chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"},
function(response){
text.innerHTML = response.data;
});
});
this method will replicate a text on the word editor but the cloned text will disappeared or not saved after we click on other area part of the text(word) editor

Related

How to turn off reload when JS function starts in Laravel

I made this clipboard copy function. it work at my Laravel. But there are some problem. I can copy but when I click the COPY button current page reload.
Another thngs is I would like to make cool design like Github'S "Clone with HTTPS" under "Use Git or checkout with SVN using the web URL. " sentence
at small window's image.
Could you teach me what is wrong my code please?
Laravel's form is here I need to write like this but when click the clipboard copy I don't want to go nextpage
<form action="{{ url('nextpage') }}" method="post">
index.blade.php
<p><span class="js-copytext">{{$post_data['somedata']}}</span></p>
<p><button class="js-copybtn">copy</button></p>
js file
<script>
var copyEmailBtn = document.querySelector('.js-copybtn');
copyEmailBtn.addEventListener('click', function(event) {
var copyText = document.querySelector('.js-copytext');
var range = document.createRange();
range.selectNode(copyText);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
} catch(err) {
console.log('error');
}
window.getSelection().removeAllRanges();
});
</script>
You need to add event.preventDefault() inside your handler.
copyEmailBtn.addEventListener('click', function(event) {
event.preventDefault();
// The rest of your code...
});

Receiving Broken Links from my Chrome Extension when I Embed Links

In the chrome extension I'm developing, I'm using document.getElementById("id").innerHTML to return results from my .js file to my HTML, but my embedded links aren't working correctly. Instead of being hyperlinked with, for example, stackoverflow.com, I'm getting links like the following: chrome-extension://ijmlokbcldclhokfgkfilhopdehmkhjh/stackoverflow.com
I couldn't find anything to help on stackoverflow, so below is my code:
chrome.tabs.executeScript({code: `
var sent_text = document.domain;
information = sent_text;
chrome.runtime.sendMessage({greeting: sent_text}, function(response) {
console.log(response.farewell);})
`});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
return_value = request.greeting.split(",")[2]; // For now, only need domain.
document.getElementById("content").innerHTML =
"<a href='" + return_value + "'>" + return_value + "</a>";
sendResponse({farewell: request.greeting});
});
To rephrase, I'm having weird, broken links that begin with "extension://".

Servlet-Response containing text (for display) as well as file download

I'm trying to download a file from my server through a Java Servlet.
The Problem I have is that when I enter the servlet url directly (https://localhost:8443/SSP/settings?type=db_backup) I get the servlet to execute its code and prompt me with a download dialog.
But I would like to call the servlets doGet method via Javascript to wrap it with a progress bar of some kind.
Problem here: Code in servlet is executed but I dont get the download prompt for the file.
My Code so far:
HTML:
<!-- Solution #1 -->
<button class="btn_do_db_backup" type="button">DB-Backup #1</button>
<!-- Solution #2 -->
<form action="/SSP/settings?type=db_backup" method="GET">
<button type="submit">DB-Backup #2</button></br>
</form>
JS:
// Solution #1
$(".btn_do_db_backup").click(function(e){
e.preventDefault();
$.get("settings?type=db_backup", function(data){
if(data != ""){
//further coding
}
});
// Having the code below works but doesnt
// give me the chance to wrap the call with a loading animation
//document.location = "/SSP/settings?type=db_backup";
});
Servlet:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// PART 1
// execute srcipt to generate file to download later on
StringBuffer output = new StringBuffer();
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "D:\\TEMP\\sql_dump.cmd");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String filename = "";
int tmp = 0;
while (true) {
line = r.readLine();
if (line == null) { break; }
output.append(line + "\n");
// code for finding filename not optimal but works for now -> redo later on
if(tmp == 1){
filename = line.substring(line.indexOf("db_backup_"), line.indexOf('"', line.indexOf("db_backup_")) );
}
tmp++;
}
// PART 2
// download the file generated above
OutputStream out = response.getOutputStream();
String filepath = "D:\\TEMP\\sql_dump\\";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
FileInputStream fileInputStream = new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
out.close();
fileInputStream.close();
}
Solution #2 works great, I get a popup to download the file.
Solution #1 calls the servlets doGet-method (via the above JS-Code and the code from my servlet is executed correctly) but I dont get a download popup
I would like to go with solution #1 though as this gives me the opportunity to wrap the $.post call with a loading animation.
What am I missing within solution #1 to get that download popup to shop up?
EDIT 1:
I found that data in the $.get() function is filled with the content of the desired file. I can now display the content of a .txt file in a div for example but I would like to donwload said .txt file instead.
EDIT 2:
Solved it, see my answer below for details & comment/ansewer if you think it can be done in a better way
after quite some time trying to get it to work I found a solution that works. There may be better ones but thats the one I came up with.
Hope this may be helpfull for others as well.
Basic explanation of what I did here:
Have a form do a GET-Request (via JS) to a java servlet
The servlet executes a commandline script (in my case a sql-dump of my postgreSQL DB)
The servlets gathers the output from the commandline and the contents of the generated file (the sql_dump) and puts them in the response
The client gets the response and cuts it into 3 pieces (commandline output, filename & contents of sql_dump-file)
Then (via JS) the commandline output is shown in a textarea for a better overview of what the script actually did
The contents of the sql_dump-file is processed by JS-Code to generate a file to download (eihter manually via a button or automatically)
So without further ado, here we go with the flow ... code :)
SOLUTION:
HTML:
<form id="form_download_db_backup">
<input type="submit" value="Create & Download DB-Backup"></br>
<a download="" id="downloadlink" style="display: none">download</a>
</form>
<div class="db_backup_result" id="db_backup_result" style="display: none;">
</br>Commandline-Output</br>
<textarea id ="txta_db_backup_result" rows="4" cols="50"></textarea>
</div>
JS:
$("#form_download_db_backup").submit(function(e){
e.preventDefault();
var spinner = new Spinner().spin();
var target = document.getElementById('content');
target.appendChild(spinner.el);
$.ajax({
url:'settings?type=db_backup',
type:'get',
success:function(data){
spinner.stop();
if(data != ""){
var str_data = "" + data;
// Cut commanline output from data
var commandline_output = str_data.substring( 0, str_data.indexOf("--End") );
//show commanline output in textarea
$("#txta_db_backup_result").html(commandline_output);
// Cut content of db_backup file from data
var sql_dump_content = str_data.substring( str_data.indexOf("--sql_d_s--") + 13,str_data.indexOf("--sql_d_e--") );//|
// Cut filename from data
var filename = str_data.substring( str_data.indexOf("--sql_d_fns--") + 15,str_data.indexOf("--sql_d_fne--") - 2 );
//-------------------------------------------------------------
// Prepare download of backupfile
var link = document.getElementById('downloadlink');
var textFile = null;
var blob_data = new Blob([sql_dump_content], {type: 'text/plain'});
// FOR IE10+ Compatibility
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob_data, filename);
}
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(blob_data);
link.href = textFile;
link.download = filename;
//link.style.display = 'block'; // Use this to make download link visible for manual download
link.click(); // Use this to start download automalically
//-------------------------------------------------------------
// show div containing commandline output & (optional) downloadlink
document.getElementById("db_backup_result").style.display = 'block';
}
}
});
});
Java-Servlet:
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String type = request.getParameter("type");
if(null != type)switch (type) {
case "db_backup":
ServletOutputStream out = response.getOutputStream();
// Prepare multipart response
response.setContentType("multipart/x-mixed-replace;boundary=End");
// Start: First part of response ////////////////////////////////////////////////////////////////////////
// execute commandline script to backup the database
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "D:\\TEMP\\sql_dump.cmd");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
String filename = "";
int tmp = 0;
while (true) {
line = r.readLine();
if (line == null) { break; }
// code for finding filename not optimal but works for now -> redo later on
if(tmp == 1){
filename = line.substring(line.indexOf("db_backup_"), line.indexOf('"', line.indexOf("db_backup_")) );
}
else{
line = line.replace("\u201E", "\'"); // replaces the lowercase " (DOUBLE LOW-9 QUOTATION MARK)
line = line.replace("\u201C", "\'"); // replaces the uppercase " (LEFT DOUBLE QUOTATION MARK)
}
out.println(line);
tmp++;
}
// End: First part of response ////////////////////////////////////////////////////////////////////////
// Separator of firt & second part
out.println("--End");
out.flush();
// Add filename in response (name of download file)
out.println("--sql_d_fns--"); // separator for filename (used to extract filename from response data)
out.println(filename);
out.println("--sql_d_fne--"); // separator for filename (used to extract filename from response data)
// Start: Second part of response ////////////////////////////////////////////////////////////////////////
out.println("--sql_d_s--"); // separator for content of db-dump (this is the text thats going to be downloaded later on)
String filepath = "D:\\TEMP\\sql_dump\\";
FileInputStream fileInputStream = new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
out.println("--sql_d_e--"); // separator for content of db-dump (this is the text thats going to be downloaded later on)
// End: Second part of response ////////////////////////////////////////////////////////////////////////
// End the multipart response
out.println("--End--");
out.flush();
break;
default:
break;
}
}
postgreSQL dump contain "lowercase" & "uppercase" quotation marks which I had to replace. I put a link to each here in case someone struggles with them as well. They have multiple encodings for those characters listed there.
Unicode Character 'DOUBLE LOW-9 QUOTATION MARK' (U+201E)
Unicode Character 'LEFT DOUBLE QUOTATION MARK' (U+201C)

Chrome Extension passing String

I'm trying to write a simple extension to decode a URL that´s given within the body of a page. I've got this contentscript:
function getText(){
var text = document.body.innerText;
return text;
}
var Text = getText();
console.log(Text);
chrome.runtime.sendMessage({ Text: Text});
and this for my popup:
function decodeURL(Encoded) {
var Decoded = decodeURIComponent(Encoded);
return Decoded;
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
localStorage["Text"] = request.Text;
console.log(localStorage["Text"]);
}
);
var List = localStorage["Text"].split(" ");
var URL = List[List.length - 1];
document.write("<a href=");
document.write(URL);
document.write(">");
document.write("Log In");
document.write("</a>");
Now my content script get´s the text and prints it to the console but the popup script doesn´t seem to be able to access it. I know this has been asked many times but none of the other Threads contained anything I could get to work.

How do I save user email as a variable when someone installs the extension?

In my bookmarking extension, I need to send the gmail address of the user to google app engine in order to write the bookmark to the database as the user as "owner".
My understanding is that I cannot use a popup because I have a background page (I remember reading about this but I could not find it again). I am also reading the installation process in Chrome store. I would appreciate if anyone can direct me to the right place in the documentation.
I copy my background.html below with the variable extension_user included. How do I get this variable from the user when they upload the extension? This is my previous question.
<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
// Send a request to the content script.
chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) {
var firstParagraph = response.dom;
var formData = new FormData();
formData.append("url", tab.url);
formData.append("title", tab.title);
formData.append("pitch", firstParagraph);
//***the variable with user email to send to backend:***//
//formData.append("extension_user", extension_user)
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}else{
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
}
}
};
xhr.send(formData);
}); //chrome.tabs.sendRequest
});
});
</script>
</html>
You can use both a popup and background page in a single extension. A lot of my extensions use both... Use the background page to communicate and save data for your popup page...
You can prompt your user to save their email address on install in your background page as follows:
<script type="text/javascript">
addEventListener('load', function(){
var MAJOR_VERSION=1.0;
if(!localStorage.updateread||localStorage.updateread!=MAJOR_VERSION)
{
var email=prompt("Enter the Email Address : ")
localStorage["Email"] = Email;
localStorage.updateread=MAJOR_VERSION
}
}, 0);
</script>
This script will only run when you first install the extension. And the users email address will be saved in the extensions LocalStorage until they uninstall... Calling this variable will now work in both your background page and your popup page...

Categories

Resources