Chrome扩展开发:从DOM中选中textarea遇到问题求助
Chrome扩展:实现textarea元素选中功能
问题背景
我已大量查阅textarea选中相关技术资料,但未找到合适的解决方案。
开发目标
我正在开发一款Chrome扩展,已成功访问页面DOM,但无法单独选中textarea元素,希望实现指定的选中效果(对应图示功能)。
相关代码文件
manifest.json
{"manifest_version": 2,"name": "DOM","version": "0.0", "background": {"persistent": false,"scripts": ["background.js"]},"content_scripts": [{"matches": ["*://*.stackoverflow.com/*"],"js": ["content.js"]}],"browser_action": {"default_title": "DOM","default_popup": "index.html"},"permissions": ["activeTab","tabs","<all_urls>"]}
index.html
<!DOCTYPE html> <html> <head>Fayzan</head> <body> <button id="test">DOM!</button> <script src="test.js"></script> </body> </html>
Content.js
// Listen for messages chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { // If the received message has the expected format... if (msg.text === 'report_back') { // Call the specified callback, passing // the web-page's DOM content as argument sendResponse(document.all[0].outerHTML); } });
background.js
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/; function doStuffWithDom(domContent) { console.log('I received the following DOM content:\n' + domContent); } // When the browser-action button is clicked... chrome.browserAction.onClicked.addListener(function(tab) { // ...check the URL of the active tab against our pattern and... if (urlRegex.test(tab.url)) { // ...if it matches, send a message specifying a callback too chrome.tabs.sendMessage(tab.id, { text: 'report_back' }, doStuffWithDom); } });
test.js
document.getElementById("test").addEventListener('click', () => { alert("DOM POPUP"); function modifyDOM() { console.log('Tab script:'); console.log(document.body); return document.body.innerHTML; } chrome.tabs.executeScript({ code: '(' + modifyDOM + ')();' }, (results) => { console.log("fayzan bhatti"); console.log(results); } ); });
内容的提问来源于stack exchange,提问作者OnlyCOde
相关产品推荐
相关产品推荐

