I am trying to use the OfficeExtension.TrackedObjects class to access a range across different contexts (documentation and similar questions set out below - although slightly outdated). The goal is to have a taskpane search list the results in the taskpane, then select the specific result in-text when clicking the listed result (using javascript).
Here is what I have:
var items = [];
function basicSearch() {
Word.run(function (context) {
const results = context.document.body.search("Online");
results.load("length, text, items");
return context.sync().then(function () {
context.trackedObjects.add(results);
for (let i = 0; i < results.items.length; i++) {
let x = results.items[i].text;
createtable("TestList", i, x, x);
items.push(results.items[i]);
}
});
return context.sync();
});
}
function createtable(id, x, y, z) {
var table = document.getElementById(id);
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.type = "button";
cell1.onclick = function () { selectrange(x) };
cell2.type = "button";
cell2.onclick = function () { selectrange(x) };
cell3.type = "button";
cell3.onclick = function () { selectrange(x) };
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
}
function selectrange(x) {
results.load("text");
results.items[x].select();
results.context.sync();
}
Could someone show me where I have gone wrong, or provide a full working example of how to track and call an object (or collection of objects) for use?
Resources:
https://learn.microsoft.com/en-us/javascript/api/office/officeextension.trackedobjects?view=common-js-preview&viewFallbackFrom=office-js How can a range be used across different Word.run contexts? Word Online Add-In: Using objects across multiple contexts Tracked Objects throwing errors in Word Online https://leanpub.com/buildingofficeaddins (Building Office Add-ins using Office.js has a working example, but it is in typescript and does not use trackedObjects - I have not been able to replicate it in my add-in).
When I run the above code, it says "ReferenceError: Can't find variable: results". I want it to select the specific search results displayed and pressed in the list. Any assistance would be greatly appreciated.
first, you need to define results as a global variable so that you can pass it to other functions. please reference the following code:
var results;
async function basicSearch() {
await Word.run(async (context) => {
results = context.document.body.search("Online");
results.track();
await context.sync();
});
}
async function selectrange() {
await Word.run(results, async (context) => {
results.load();
await context.sync();
results.items[0].select();
await context.sync();
});
}