Javascript 如何重写网页chrome.extension.executeScript的代码
我正在编写一个chrome扩展,需要能够将代码添加到它正在查看的网页中。现在在我的背景页上我有Javascript 如何重写网页chrome.extension.executeScript的代码,javascript,javascript-events,google-chrome-extension,javascript-injection,Javascript,Javascript Events,Google Chrome Extension,Javascript Injection,我正在编写一个chrome扩展,需要能够将代码添加到它正在查看的网页中。现在在我的背景页上我有 chrome.tabs.onUpdated.addListener(function(tabId, info) { if (info.status=="complete") { chrome.tabs.executeScript(null, {file: "injectme.js"}) } }) 以及注入的脚本injectme.js,其中包含如下函数 function
chrome.tabs.onUpdated.addListener(function(tabId, info) {
if (info.status=="complete") {
chrome.tabs.executeScript(null, {file: "injectme.js"})
}
})
以及注入的脚本injectme.js
,其中包含如下函数
function() {
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}
我的问题是如何在加载时调用此函数,以便它可以将脚本插入网页。如果我理解您的意思:)
您需要做的就是将当前函数扭曲到如下内容中:
(function () {
// your code
if (!document.getElementById('searchforme')) {
x=document.createElement('script')
x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
x.setAttribute('id','searchforme')
document.appendChild(x)
alert('it is finished')
} else {
alert('so close')
}
}());
因此,它将是一个“即时调用”函数。加载什么的时刻?页sites.google.com脚本?查看页面源代码时是否存在
searchforme
元素,或者稍后将其添加到页面中?