function selectTextOnly(containerid) {
var text = document.getElementById(containerid);
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}The if stament is used to check document.body.createTextRange used only for IE; the else for all other browsers.
我正在研究将选定/突出显示的文本复制到textarea的chrome扩展。这是我迄今使用:
chrome.tabs.executeScript({
code: "window.getSelection().toString();", }, function(selection) {
document.getElementById("output").value = selection[0]; }); 但现在我已经从popup.html切换到我喜欢这个
background.js创建的窗口:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
url: chrome.runtime.getURL("window.html"),
type: "panel", height: 590, width:850, focused: false
}, function(win) {
}); }); 我无法将选定的文本放入此窗口中。我也复制了activetab当前URL做像这样:
chrome.tabs.getSelected(windowId, function(tab) {
document.getElementById('url').innerHTML = tab.url;
var windowId = tab.id
}); ,我可以这样工作,为新窗口使用make:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
document.getElementById('url').innerHTML = tabs[0].url; }); 所以我的问题是:我如何获得选中/突出显示文本到我新创建的窗口内的textarea?是否有类似的东西在
chrome.tabs.query()
只为突出显示的文本?
使用executeScript的tabId参数点击的标签注入,然后通过使用任何这些文字:
下面是localStorage的一个例子。
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
getSelectedText(tab.id, function(text) {
localStorage.selectedText = text;
chrome.windows.create({
url: "/window.html",
type: "panel", height: 590, width:850, focused: false
});
}); }); function getSelectedText(tabId, cb) {
chrome.tabs.executeScript(tabId, {
code: "window.getSelection().toString();",
}, function(selection) {
cb(selection[0]);
}); } window.html:
................. <script src="window.js"></script> </body> </html>
window.js:
document.getElementById('url').textContent = localStorage.selectedText || ''; delete localStorage.selectedText; document.getElementsByTagName('p')[0].onmouseup = function() {
if (typeof window.getSelection === 'function') {
//code
var selObj = window.getSelection();
alert(selObj);
var selRange = selObj.getRangeAt(0);
} else if (document.selection) {
alert(document.selection.createRange().htmlText) //IE6 7 8
}
}