0
我想創建一個Chrome瀏覽器插件,以便在網上閱讀文章。我希望用戶可以選擇他想要閱讀文章的速度,插件可以用相同的速度突出顯示文章的文字(每個單詞)。這可以通過使用網頁的JavaScript修改CSS來實現,但CSS中的更改只有在執行完整的JavaScript並且所有更改都一次反映而不是一次一個單詞時纔可見。可以用不同的方式實現它。以下是我的代碼。使用javascript修改網頁的CSS
background.js
/* Regex-pattern to check URLs against.
It matches URLs like: http[s]://[...]stackoverflow.com[...] */
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?getpocket\.com/;
/* A function creator for callbacks */
function doStuffWithDOM(element) {
alert("I received the following DOM content:\n" + element.toString());
}
/* 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);
}
});
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
//var outerHTML = document.querySelector('.text_body').outerHTML;
//sendResponse(document.all[0].outerHTML);
//var outerHTML = document.all[0].outerHTML;
var outerHTML = document.querySelector('.text_body').outerHTML;
var outerHTML1 = outerHTML;
var j=0;
var k = 0;
var searchText = ' ';
for(i=outerHTML.indexOf(searchText);i<outerHTML.length;i = outerHTML.indexOf(searchText,i+1))
{
outerHTML1 = "<mark>" + outerHTML1.substring(0,i)+ "</mark>"+ outerHTML1.substring(i+1,outerHTML1.length-1);
for(k=0;k<500;k++)
{
console.log(k);
}
k = 0;
document.querySelector('.text_body').outerHTML = outerHTML1;
//sendResponse(document.querySelector('.text_body').outerHTML);
console.log(i);
}
sendResponse("it works!");
/*for (index = outerHTML.indexof(" ") , index1 = 0; index < outerHTML.length() ; index1 = index ,index = outerHTML.indexof(index , " "))
{
outerHTML = outerHTML.substring(index1,index-1) + "<span class='highlight'>" + outerHTML.substring(index1,index+text.length) + "</span>" + outerHTML.substring(index + text.length);
inputText.outerHTML = outerHTML
}*/
}
});
的manifest.json
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.getpocket.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
因此改變CSS只有當部分映入眼簾,而不是整個頁面將是配不上你? –
是的,那會很好,但是網頁內容的CSS應該逐字改變。 – user2177859