[英]How can I start a function everytime the page loads?
(如有英文錯誤敬請見諒)
大家好,我正在開發一個簡單的 Chrome 擴展程序來編輯網站 (Freshdesk) 的一些圖形和文本相關字段,我無法從網站本身修改這些字段,因為代碼是專有的。
我的問題是,為了使每次顯示頁面時替換文本的 function 都處於活動狀態,我使用了具有 100 毫秒延遲的 setInterval(),這有點工作但不是最佳的,因為 function 運行得像數千幾秒鍾內的次數。
function main() {
console.log('main started');
setInterval(changeText, 100); //(Not optimized)
}
function changeText() {
// replace 'Group' with 'Sector'' in the ticket tab visual
$('.ember-power-select-placeholder.label-field').each(function(x){
var new_text = $(this).text().replace("Group", "Sector");
$(this).text(new_text);
console.log('function started');
})
}
main();
正如您從上面的屏幕截圖和代碼中看到的那樣,在這個簡單的例子中,我想將文本從
團體
到
部門
而且,如您所見,代碼有效,但如果我們看一下控制台...... (大約 5 秒后)。
我已經嘗試了一些 function 讓 js 在頁面加載一次后立即運行,但它們似乎都不適合我。 你有什么技巧可以解決這種情況嗎?
編輯:這也是 manifest.json
{
"name": "DAN-Patch",
"version": "1.0",
"manifest_version": 2,
"permissions": [
"webNavigation",
"activeTab",
"background",
"tabs"
],
"content_scripts": [
{
"run_at": "document_idle",
"matches": ["https://gestionaledan.freshdesk.com/*", "https://gestionaledan.freshworks.com/*"],
"js": ["jquery-3.5.1.min.js", "content.js"],
"css": ["stylesheet.css"]
}
]
}
使用它來減少進程數:
function main() {
console.log('main started');
let exa = setInterval(function () {
let el = $('.ember-power-select-placeholder.label-field'),
all = 0;
el.each(function () {
if ($(this).text() == "Group") {
// replace 'Group' with 'Sector'' in the ticket tab visual
var new_text = $(this).text().replace("Group", "Sector");
$(this).text(new_text);
console.log('function started');
all ++;
}
});
if (all == 0) {
clearInterval(exa);
}
}, 100); //(Not optimized)
}
main();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.