How can i delete the Bookmark in word using js api or is this the way to delete the bookmark as i tried? - ms-word

the error is showed in image please check
Here is the code for deleting the bookmark from word addin using js api
Word.run(async (context) => {
console.log("result", result);
const range :any = context.document.getSelection();
return context.sync().then(async function ()
{
context.load(range);
await context.sync();
let text = range.text
console.log("item", item.ImageId, text);
if (item.ImageId == text) {
console.log("item bookmark",item.bookmark)
range.hyperlink = "#" + item.bookmark;
//delete the bookmark after 5 sec
setTimeout(()=>{
console.log("setTimeout called")
range.deleteBookmark(item.bookmark)
},5000)
} else {
console.log("range not matched");
}
await context.sync();
});

Related

Office-js Commands.js function Not executing

I have a simple function that when clicking it on a button it changes the font color. For some reason these are the only functions not working / registering. This is the commands.ts file under the commands folder directly under src.
The button is in the manifest.xml file that is under its own group and I have verified that they match. That is what the event.source.id is.
async function changeColor(event) {
Word.run(async (context) => {
await context.sync();
const selectedText = context.document.getSelection();
selectedText.load();
await context.sync();
switch (event.source.id) {
case "Blue.Button":
selectedText.font.color = "#08437A";
await context.sync();
break;
case "Orange.Button":
selectedText.font.color = "#EA7C1D";
await context.sync();
break;
case "Green.Button":
selectedText.font.color = "#8EAB4D";
await context.sync();
break;
case "Purple.Button":
selectedText.font.color = "#1B1630";
await context.sync();
break;
case "Yellow.Button":
selectedText.font.color = "#FFCF01";
await context.sync();
break;
default:
selectedText.font.color = "#CCCCCC";
await context.sync();
break;
}
await context.sync();
});
event.completed();
}
function getGlobal() {
return typeof self !== "undefined"
? self
: typeof window !== "undefined"
? window
: typeof global !== "undefined"
? global
: undefined;
}
const g = getGlobal();
Office.actions.associate("changeColor", changeColor);
I am in a Typescript React project but I have tried changing the file to .js and .ts even though it should work either way to eliminate any bugs. I have looked at the docs and I notice that the Office.actions.associate is new and that is the new way to call the function. Any recommendations?
I found the solution, it was in my webpack.config.js file
before:
new HtmlWebpackPlugin({
filename: "taskpane.html",
template: "./src/taskpane/taskpane.html",
chunks: ["taskpane", "vendor", "polyfills"],
})
after:
new HtmlWebpackPlugin({
filename: "taskpane.html",
template: "./src/taskpane/taskpane.html",
chunks: ["taskpane", "vendor", "polyfills", "commands"],
})
Turns out I missed putting the "commands" within the taskpane since that is where it was residing.

How to redirect to an image while click on test or id in word addin using office js?

please view the attached image for output
this is the code I have written in js
Office.context.document.addHandlerAsync(
Office.EventType.DocumentSelectionChanged,
(result: any) => {
let bookmark = localStorage.getItem("bookmark")
let bookmarkParse = JSON.parse(bookmark);
console.log("bookmarkParse",bookmarkParse)
bookmarkParse.map((item: any) => {
Word.run(async (context) => {
console.log("result", result);
const range = context.document.getSelection();
console.log("getRange",range)
return context.sync().then(async function ()
{
context.load(range);
await context.sync();
let text = range.text
console.log("item", item.ImageId, text);
if (item.ImageId == text) {
console.log("item bookmark",item.bookmark)
range.hyperlink = "#" + item.bookmark;
console.log("range.hyperlink",range.hyperlink)
console.log(item.bookmark,"range matched");
} else {
console.log("range not matched");
}
await context.sync();
});
here is the my code for redirected to image when clicking on the test.

Inserting watermark in Word

I would like to insert a watermark into a Word document using Office.js. I am able to insert the watermark DRAFT using the sample code from: https://github.com/OfficeDev/Word-Add-in-JS-Watermark/blob/master/WatermarksManagerWeb/Home.js. The sample code places the watermark all on pages.
I am interested in a simpler solution than the one below that places the watermark only on the first page. Thank you.
(function () {
"use strict";
var messageBanner;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
$('#createWM').click(insertWaterMark);
$('#deleteWM').click(removeWM);
$('#txtWM').val("DRAFT");
});
};
function insertWaterMark() {
Word.run(function (ctx) {
var mySections = ctx.document.sections;
ctx.load(mySections);
// ctx.document.body.insertOoxml(mywatermark, "end");
return ctx.sync().then(function () {
var myWatermark = getWM($('#txtWM').val());
var myHeader = mySections.items[0].getHeader("primary");
var myRange = myHeader.insertOoxml(myWatermark, "replace");
var myCC = myRange.insertContentControl();
myCC.title = "myTempCC";
myCC.appearance = "hidden";
return ctx.sync();
});
}).catch(function (e) {
app.showNotification(e.message, e.description);
});
}
function getWM(text) {
var mywatermark = "<?xml version=\"1.0\" standalone=\"yes\"?>\r\n<?mso-application progid=\"Word.Document\"?>\r\n<pkg:package xmlns:pkg=\"http://schemas.microsoft.com/office/2006/xmlPackage\"> ... THE REST OF THE OPENXML content for watermark ...</pkg:package>\r\n";
return (mywatermark.replace("CONFIDENTIAL", text));
}
Update: I think I have an idea how to get the watermark on the first page. I implemented the solution, but it doesn't show the watermark. Please look at my code and let me know if you see anything wrong with it.
var mySections = ctx.document.sections;
ctx.load(mySections);
return ctx.sync().then(function () {
var myWatermark = getWM("DRAFT");
var myHeader = mySections.items[0].getHeader(Word.HeaderFooterType.firstPage);
mySections.items[0].headerFooterFirstPageDifferent = true;
var myRange = myHeader.insertOoxml(myWatermark, "replace");
var myCC = myRange.insertContentControl();
myCC.title = "myTempCC";
myCC.appearance = "hidden";
return ctx.sync();
I looked in the documentation, here on stackoverflow, on github and in several places but I couldn't find any solution that would help me to insert a watermark in the page header.
But after a few days of difficulty, I was testing all possible methods and combinations of use until I managed to understand how to insert the watermark. And it's simpler than I thought. Too bad this isn't in Microsoft Docs.
return Word.run( (context) => {
context.document.sections.getFirst().getHeader().insertParagraph('WaterMark', Word.InsertLocation.start);
context.sync();
});
I figured out how to insert a real watermark into the body of a document.
private async insertWatermark(): void {
await Word.run(async (context) => {
const paragraphs = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary).paragraphs;
paragraphs.load("$none");
await context.sync();
const newParagraph = paragraphs.getLastOrNullObject();
let contentControl = newParagraph.insertContentControl();
contentControl.insertOoxml(this.addWatermarkText("My Watermark Text"), Word.InsertLocation.end);
await context.sync();
}
private addWatermarkText(text: string = "My Watermark"): string {
const watermark: string = 'Watermark Content HERE';
return watermark.replace("WATERMARK", text);
}
Get Watermark content in this link for replace this code snippet 'Watermark Content HERE'

Can't update title in desktop version of word

I have an Office Addin and am trying to update the title of the document on desktop. i have tried 2 diffrent ways and none of them works on hte desktop. It works fine on word online but not on the desktop.
Word.run(async (context) => {
var newTitle = document.getElementById("inputTitle") as HTMLInputElement;
console.log(newTitle.value);
context.document.properties.title = newTitle.value;
});
This code works online but not on the desktop. I have also tried doing doing it in this way.
Office.context.document.customXmlParts.getByNamespaceAsync("http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
function (resultCore) {
var xmlPart = resultCore.value[0];
xmlPart.getNodesAsync('*/*', function (nodeResult) {
for (var i = 0; i < nodeResult.value.length; i++) {
var node = nodeResult.value[i];
console.log("BaseName: ")
console.log(node.baseName);
if (node.baseName === "title") {
var newTitle = document.getElementById("inputTitle") as HTMLInputElement;
console.log("title that you entered: " + newTitle.value);
console.log(node);
node.setNodeValueAsync(newTitle.value, { asyncContext: "StateNormal" }, function (data) { });
}
}
});
});
Does anyone know why it doesn't work or have some other solution to my problem?
The following code works for me, including on desktop. Note that you have to await the Word.run. Also, you have to load the title and then sync to make sure you have changed the title on the actual document and not merely in the proxy object in your task pane code.
await Word.run(async (context) => {
var newTitle = document.getElementById("inputTitle") as HTMLInputElement;
console.log(newTitle.value);
context.document.properties.title = newTitle.value;
const myProperties = context.document.properties.load("title");
await context.sync();
console.log(myProperties.title);
});

How to come out of method execution based on a condition in protractor?

I'm a Java developer and new to protractor. I'm trying to iterate through a dynamic web table in a web page and trying to find out a particular user name and open his profile. Once I open his profile, I want my test method to stop execution and return. But the return statement doesn't work and the for loop still runs. Could anyone please help me with this? Below is my method.
searchUser() {
// Iterate through the user listing table
browser.driver.findElement(by.css('.slds-max-medium-table--stacked-horizontal')).then(function (table) {
table.findElement(by.tagName('tbody')).then(function (tbody) {
tbody.findElements(by.tagName('tr')).then(function (rows) {
for (var i = 0; i < rows.length; i++) {
rows[i].findElements(by.tagName('td')).then(function (cols) {
cols[1].getText().then(function (user) {
if (user == "ADAM SMITH") {
// found user, open his profile
cols[1].click();
return;
}
});
});
}
// user not found in the current page. Click on next page and continue search
element(by.xpath("//*[#id='main']/div/app-users-profile/users-listing/form/div[2]/div/div/div/div[2]/div/button")).click();
browser.sleep(3000);
var currentPage = new LoginPage();
currentPage.searchUser();
});
});
});
}
I try to make as less differences as I can.
async function searchUser () {
let result = false;
while (!result) {
const table = browser.$('.slds-max-medium-table--stacked-horizontal');
const tbody = table.$('tbody');
const rows = tbody.$$('tr');
await rows.map(async (row) => {
const column = row.findElements(by.tagName('td')).get(1);
const name = await column.getText();
if (name === 'ADAM SMITH') {
await column.click();
result = true;
}
});
if (!result) {
await element(by.xpath("//*[#id='main']/div/app-users-profile/users-listing/form/div[2]/div/div/div/div[2]/div/button")).click();
await browser.sleep(3000);
const currentPage = new LoginPage();
await currentPage.searchUser();
}
}
}