I am new to Microsoft Office addins and JS. I am trying to develop a Microsoft Word add-in that converts selected text in the document into QR code. So my problem is getting selected text in the document as simple string.
Nothing I tried so far worked. Here is a link for getting the whole text in a document that helped a bit: Word Add-in Get full Document text?. What I need is how to get selected text as a string. I need your help please. I tried the following:
txt = "";
await Word.run(async (context) => {
var documentBody = context.document.body;
context.load(documentBody);
return context.sync().then(function () {
console.log(documentBody.text); //full document text
console.log(document.getSelection.text); //selected only
txt = documentBody.text.getSelection();
});
});
Check the Script Lab. The first sample in Word does exactly what you need:
$("#run").click(() => tryCatch(run));
function run() {
return Word.run(function(context) {
var range = context.document.getSelection();
range.font.color = "red";
range.load("text");
return context.sync().then(function() {
console.log('The selected text was "' + range.text + '".');
});
});
}
/** Default helper for invoking an action and handling errors. */
function tryCatch(callback) {
Promise.resolve()
.then(callback)
.catch(function(error) {
// Note: In a production add-in, you'd want to notify the user through your add-in's UI.
console.error(error);
});
}
Related
I'm trying to create a sort of dropdown menu that a user can insert tokens into a CKEditor with. I've found that I can insert text in an editor with this code:
editorInstance.model.change( writer => {
let pos = editorInstance.model.document.selection.getFirstPosition();
writer.insertText( "TEST", pos,0);
});
It works when I put it in the ClassicEditor.create.then for testing but it does nothing when I place this in a $().click event. I can log something from inside the callback so I know the code is executed but nothing is inserted.
I've been trying to get this working for hours now but all the examples I can find is in angular or any other frameworks.
I Solved the issue you faced as follows
first defined new editor that is null and Then instatiate Ckeditor 5
let neditor = null;
ClassicEditor.create(document.querySelector('#editor'))
.then(editor => {
neditor = editor;
})
.catch(error => {
console.error(error);
});
using pure js
document.addEventListener("click", (event) => {
var button = event.target;
if (event.target.type === 'button' && event.target.className.includes('testtokenbutton')) {
neditor.model.change(writer => {
const insertPosition = neditor.model.document.selection.getFirstPosition();
writer.insertText(button.id, insertPosition);
});
}
});
I have the following code that is pulling from inline JS on a webpage to pull the webID. This is being used for a Chrome extension that will display just the site's webID when clicked:
// payload.js script --> insert into the current tab after the popout has loaded
window.addEventListener('load', function (evt) {
chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
file: 'payload.js'
});;
});
//popout.html
chrome.runtime.onMessage.addListener(function (message) {
document.getElementById('body').innerHTML = message;
chrome.tabs.executeScript({
code: '(' + (() => {
for (var el of document.querySelectorAll('script[if="inlineJs"]'))
{
var m = el.textContent.match(/"([^"]*webId*[^"]*)"/);
var webid = m
if (webid) return webid[1];
else {return document.getElementById('body').innerHTML = "This is not a CDK site";}
}
}) + ')()',
}, results => {
if (!chrome.runtime.lastError && results) {
document.getElementById('body').textContent = decodeURI(results[0]);
}
});
});
Currently this returns the following:
{"cache":{"Co.context.configCtx":{"webId":"gmps-salvadore","locale":"en_US","version":"LIVE","page":"HomePage","secureSiteId":"b382ca78958d10048eda00145edef68b"},"features":{"directivePerfSwitch":true,"enable.directive.localisation":true,"enable.directive.thumbnailGallery":true,"enable.new.newstaticmap":false,"disable.forms.webId":false,"use.hydra.popup.title.override.via.url":true,"enable.directive.geoloc.enableHighAccuracy":true,"use.hydra.theme.service":true,"disable.ajax.options.contentType":false,"dealerLocator.map.use.markerClustering":true,"hydra.open.login.popup.on.cs.click":false,"hydra.consumerlogin.use.secure.cookie":true,"use.hydra.directive.vertical.thumbnailGallery.onpopup":true,"hydra.encrypt.data.to.login.service":true,"disable.dealerlocator.fix.loading":false,"use.hydra.date.formatting":true,"use.hydra.optimized.style.directive.updates":false,"hydra.click.pmp.button.on.myaccount.page":true,"use.hydra.fix.invalid.combination.of.filters":true,"disable.vsr.view.from.preference":false}},"store":{"properties":{"routePrefix":"/hydra-graph"}}}
I would like it to just return the 'gmps-salvadore'. This would be used on multiple sites and the webID will change from site to site with differing prefixes from "lex" to "motp". Is it possible to have the extension only pull the webID from various sites?
I'm attempting to automate application process for a website I work on. I'm using selenium web-driver and node.js. I'm able to navigate through the different pages but I'm unable to get any text in the input fields. Can someone assist me with this? Please see my code below.
"use strict";
var webdriver = require('selenium-webdriver');
var browser = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();
function clickLink(link) {
link.click();
}
function handleFailure(err) {
console.error('Something went wrong\n', err.stack, '\n');
closeBrowser();
}
function createOptumID() {
return browser.findElements(webdriver.By.id('createOptumID')).then(function(result) {
return result[0];
});
}
function newOptumID() {
return browser.findElements(webdriver.By.id('firstNameId_input')).then(function(result) {
return result[0];
});
}
function closeBrowser() {
browser.quit();
}
browser.get('https://qa-ind.mahealthconnector.optum.com/individual/');
browser.findElement(webdriver.By.id('enrollment')).click();
browser.wait(createOptumID, 100000).then(clickLink);
browser.wait(newOptumID, 100000).then(clickLink);
browser.findElement(webdriver.By.id('firstNameId_input')).sendKeys('Erin');
Use the executeScript method of webdriver object like the following:
//runs the script get the element by id then set it's value attribute to 'Erin'
webdriver.executeScript("document.getElementById('firstNameId_input').setAttribute('value', 'Erin')");
You can get value of input field by using getAttribute method of webelement
browser.findElement(webdriver.By.id('firstNameId_input')).getAttribute("value");
I want to create a chrome extension that takes in some text, then opens a website, and tries to write that text to the textfield.
This is what I have:
chrome.omnibox.onInputEntered.addListener(
function(text) {
chrome.tabs.create({url:"http://www.editpad.org/"});
document.getElementById("text").value = txt; //.innerHTML = txt
alert('You just typed "' + text + '"');
});
I got the ID from just inspecting the element.
What do I need to do so it writes?
Your code runs in the context of the (invisible) background or event page. In order to "switch" to the execution context of the page you've just opened, you need to use a content script (programatically, "on the fly", using chrome.tabs.executeScript).
The annotated code below shows how to achieve the result you want.
chrome.omnibox.onInputEntered.addListener(function(text) {
chrome.tabs.create({
url: 'http://www.editpad.org/'
}, function(tab) {
// chrome.tabs.executeScript takes a string that will be parsed and run
// as JavaScript code. To pass a string, you need to make sure that it
// does not contain any invalid characters. This can easily be achieved
// by serializing the input string to JSON.
var serializedValue = JSON.stringify(text);
chrome.tabs.executeScript(tab.id, {
code: 'document.getElementById("text").value = ' + serializedValue,
}, function(result) {
if (!result) {
// This usually happens when you do not have the permission to
// run code in the page. Add the site to the "permissions"
// section manifest.json.
alert('Failed to run content script.\n' +
chrome.runtime.lastError.message);
return;
}
// The value of the last expression is passed to the callback of
// chrome.tabs.executeScript, for each frame. The code runs only in
// the top-level frame (because `allFrames: true` is not specified),
// so the result is an array with only one element.
alert('You just typed: "' + result[0] + '"');
});
});
});
I'm developing a Chrome extension which sends the highlighted selection to a speech engine API. I want to implement both context menu and on icon click. Here's the problem:
This works perfectly:
chrome.contextMenus.create({
"title" : "Speak Me",
"contexts" : ["selection"],
onclick: function (info, tab) {
speakMe(info.selectionText);
}
});
Directly underneath it I have:
chrome.browserAction.onClicked.addListener(function() {
speakMe(info.selectionText);
});
Which doesn't work.
If I leave the parameter empty it returns an audio saying "Undefined". So I guess the speech engine is telling me it got no text. What am I doing wrong?
This is the function in question, placed above:
var speakMe = function (text) {
var key, lang, url, audio;
key = "key=12345678910";
lang = "sv_se";
url = "http://tts.engine.com/api/speak?" + key + "&lang=en_us&voice=male1&speed=100&audioformat=ogg&oggbitrate=100&text=" + text;
audio = new Audio(url);
audio.play();
};
The selection text comes from another JS file:
function getSelectedText() {
var text = "";
if (typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
But since the context menu works perfectly, I don't think there's a problem with that. It's just the browserAction that I don't get how to use properly.
Because the browser action's onClicked event doesn't have any information about the selected text. You need to figure it out yourself. You can inject a content script into the current page and get the selected text with window.getSelection().toString(). Then send the message back to the extension and speak the text.
Here's an example:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,
{code: 'window.getSelection().toString()'}, function(results) {
alert(results[0]);
});
});
It just shows an alert, but it's very easy to change it to call speakMe.