如何在 Microsoft Word Online 文档中获取用户选择

How to get user selection in the Microsoft Word Online documents

我正在创建一个 Chrome 扩展,它应该与 Microsoft Word Online 文档中的用户选择交互 - 添加新的突出显示而不是自然选择突出显示,然后将其删除。 问题是我无法获得用户选择:window.getSelection() returns 的响应结果就像选择是空的。

以下是我的扩展程序中的文件:

manifest.json

{
    "manifest_version": 2,
    "name": "The extension name",
    "version": "1.0",
    "description": "This extension description",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

    "icons": {
        "128": "icon.png"
    },

    "content_scripts": [{
        "matches": ["<all_urls>"],
        "js": ["content_script.js"],
        "run_at": "document_end",
        "all_frames": true
    }],

    "permissions": ["activeTab"]
}

popup.html

<!doctype html>
<html>
<head>
    <script src="popup.js"></script>
</head>
<body>
    <div id="wrapper">
        <form id="settings" name="settings">
            <div id="apply" class="form-row">
                <input type="submit" name="apply" value="Apply"/>
            </div>
        </form>
    </div>
</body>
</html>

popup.js

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("settings").addEventListener("submit", function (e) {
        e.preventDefault();

        chrome.tabs.executeScript(null, {file: 'toolbar.js'}, function() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {});
            });
        );
    }, false);
});

toolbar.js

function showToolbar() {
    var dom_body = document.getElementsByTagName('body')[0];
    var tb_wrapper = document.createElement('div');
    tb_wrapper.id = "toolbar_wrapper";

    var tb_toolbar_play = document.createElement('button');
    tb_toolbar_play.id = "toolbar_play";
    tb_toolbar_play.title = "Play";
    tb_toolbar_play.value = "Play";

    tb_wrapper.appendChild(tb_toolbar_play);
    dom_body.appendChild(tb_wrapper);
}

showToolbar();

content_script.js

function playButtonOnClickEventListener(request, sender, sendResponse) {
    var toolbar = document.getElementById("toolbar_wrapper");

    if (toolbar !== null) {
        var toolbar_play_button = document.getElementById("toolbar_play");
        toolbar_play_button.addEventListener("click", function (e) {
            var selection = window.getSelection();
            console.log(selection);
        });
    }

    sendResponse({data: "response", success: true});
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    playButtonOnClickEventListener(request, sender, sendResponse);
});

所以,在 console.log(selection) 执行后,我想在 Chrome 开发人员工具中看到的内容:

我实际得到的是:

P.S。该扩展与 Google Docs 完美配合。

我不确定 Word Online 编辑器是如何构建的或者为什么不能使用 window.getSelection(),但我立即注意到的一件事是,当您 select 在其中输入文本时,编辑器给该文本一个 Selected class。所以也许你可以以某种方式利用它?覆盖相关元素的样式?

也许您可以使用 MutationObserver 并查找添加到元素中的 class 名称。您将不得不进行一些试验,看看这是否满足您的需求,显然,如果 Microsoft 更改 class 名称或行为,您的扩展将中断。

尝试 select 输入一些文本并放入

document.getElementsByClassName("Selected")[0].innerHTML

在控制台中。

这是问题的解决方案。希望它能对某人有用一次。

目前我看到的全貌不同了,所以我改变了文件的数量和内容。

manifest.json

{
    "manifest_version": 2,

    "version": "1.1.1",

    "name": "Test name",

    "description": "Test description",

    "browser_action": {
        "default_icon": "icon.png"
    },

    "icons": {
        "128": "icon.png"
    },

    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content_script.js"],
            "run_at": "document_end",
            "all_frames": true
        }
    ],

    "permissions": ["activeTab"]
}

content_script.js

//Word Online pages contain several different iframes, so, in order 
//to find the one where the text that we are going to work with 
//is placed, we have to use the Chrome Runtime API and its 
//"sendMessage" method that works in every frame.
//https://developer.chrome.com/apps/runtime#method-sendMessage

chrome.runtime.sendMessage("", function() {
    if (checkFrameLocation()) {
        showToolbar();
    }
});

function checkFrameLocation() {
    //So as I work with documents in OneDrive (onedrive.live.com) 
    //and in Sharepoint (<USER_NAME>-my.shrepoint.com), I found out 
    //that I need iframes with these URLs only.

    var trusted_urls = [
        "https://euc-word-edit.officeapps.live.com",
        "https://word-edit.officeapps.live.com",
        "nl1-word-edit.officeapps.live.com"
    ];

    var result = false;

    for (var i = 0; i < trusted_urls.length; i++) {
        if (window.location.href.indexOf(trusted_urls[i]) > -1) {
            result = true;
        }
    }

    return result;
}

function showToolbar() {
    var dom_body = document.body;

    var tb_wrapper = document.createElement('div');
    tb_wrapper.id = "toolbar_wrapper";
    tb_wrapper.style.position = "absolute";
    tb_wrapper.style.top = "200px";
    tb_wrapper.style.left = "200px";
    tb_wrapper.style.backgroundColor = "#ffffff";
    tb_wrapper.style.height = "30px";
    tb_wrapper.style.width = "50px";

    var tb_play = document.createElement('button');
    tb_play.id = "toolbar_play_button";
    tb_play.title = "Play";
    tb_play.innerHTML = "&#9658;";
    tb_play.style.height = "100%";
    tb_play.style.width = "100%";
    tb_play.style.lineHeight = "12px";

    tb_play.addEventListener("click", function() {
        playButtonOnClickEventListener();
    });

    tb_wrapper.appendChild(tb_play);
    dom_body.appendChild(tb_wrapper);
}

function playButtonOnClickEventListener() {
    //Now we can use the window selection object

    var window_selection = window.getSelection();
    console.log(window_selection);

    //Also, Word Online adds special class name to every selected element
    //in the document. So, this is another way to get the selected text.

    var elements_selection = document.getElementsByClassName("Selected");
    console.log(elements_selection);
}

这是证明截图:

There are results of accessing the selected text in the Word Online document