Javascript 如何用另一个文本替换页面上的选定文本?
我试图用另一个文本替换所选文本,该文本具有从关联菜单调用的函数switchTextJavascript 如何用另一个文本替换页面上的选定文本?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我试图用另一个文本替换所选文本,该文本具有从关联菜单调用的函数switchText function switchText(info) { var text = info.selectionText; // selected text // then I do some manipulations with 'text' and get 'text_to_replace' var text_to_replace = "some text"; // text to replace
function switchText(info) {
var text = info.selectionText; // selected text
// then I do some manipulations with 'text' and get 'text_to_replace'
var text_to_replace = "some text"; // text to replace
}
alert(text)和alert(text\u to\u replace)工作正常,但我正试图在页面上替换选定的文本,但我不知道如何操作。我尝试了不同的方法,但都不管用。需要特殊许可吗?如果这是一个愚蠢的问题,我很抱歉,我是JS初学者。更新以Id为目标的html元素
document.getElementById("idtotarget").innerHTML = switchText(document.getElementById("idtotarget").innerHTML)
如果您希望能够在页面上的任何位置执行此操作,则需要能够为您的选择设置某种标识ID。您必须通过某种内容脚本来实现这一点。你可以在网站上阅读更多关于它的信息 此代码允许您更改单个选择的文本 (仅在铬中测试)
功能开关文本(id){
//获取选择范围
//这是从蒂姆下来的,链接如下
变量范围,sel=window.getSelection();
if(sel.rangeCount&&sel.getRangeAt){
范围=选择范围(0);
}
//创建新的节点范围
document.designMode=“on”;
如果(范围){
选择removeAllRanges();
选择添加范围(范围);
}
//这是来自用户YeppThatsMe,也链接到下面
document.execCommand(“insertHTML”,false,“+document.getSelection()+”);
document.designMode=“关闭”;
//可以使用变量或字符串
var someNewText=“--您可以随心所欲地制作它--”;
//查找新范围并用新文本替换所选内容
document.getElementById(“自己的id”).innerHTML=someNewText;
};
源脚本
遗言
我没有花费太长的时间进行测试,脚本的原样只会改变每页的一个选择。您需要调整函数获取标记和属性信息的方式(将其更改为
getElementsByClassName
?)以多次运行它,但这应该可以工作。文本将进入html元素?文本可以位于任何html元素中。使用鼠标选择的任何文本没有特定ID,所选文本可以位于任何页面的任何位置。
function switchText(id) {
// Gets the selection range
// This is from Tim Down, linked below
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
// Creates a new node range
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// This is from user YeppThatsMe, also linked below
document.execCommand("insertHTML", false, "<span id='own-id'>"+ document.getSelection()+"</span>");
document.designMode = "off";
// You can use either a variable or a string
var someNewText = "-- You can make this whatever you want --";
// Finds the new span and replaces the selection with your new text
document.getElementById("own-id").innerHTML=someNewText;
};