chrome.tabs.executeScript:当我尝试将图像插入特定网站时不起作用

时间:2013-11-22 16:10:10

标签: javascript google-chrome google-chrome-extension

我试图将图像插入Amazon.com

首先,我确认以下代码在Chrome控制台中运行良好

insertPlace = document.getElementById("rightCol")
myImage = document.createElement("image")
myImage.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/200px-Rotating_earth_%28large%29.gif"
myImage.onclick = function() {alert(insertImage.value)}
alert("insertImage running")
insertPlace.insertBefore(myImage)

但是,当我将此代码组合成chrome扩展格式时,它似乎不再起作用了。我在manifest.json中添加了“tabs”,“”,“activeTab”权限,以下代码是background.js

function insertImage() {
insertPlace = document.getElementById("rightCol")
myImage = document.createElement("image")
myImage.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Rotating_earth_%28large%29.gif/200px-Rotating_earth_%28large%29.gif"
myImage.onclick = function() {alert(insertImage.value)}
alert("insertImage running")
insertPlace.insertBefore(myImage)}
function execute () {
chrome.tabs.executeScript(null, 
                   insertImage());
}
chrome.tabs.onCreated.addListener(function(tabId, changeInfo, tab) {         
execute();
});

1 个答案:

答案 0 :(得分:2)

executeScript函数类似于eval函数,因为它接受它执行的一串代码。您正在尝试传递insertImage函数的结果(为空)。要使脚本生效,必须将所有相关的JS代码作为字符串注入:

function execute() {
    var script = insertImage.toString() + 'insertImage();';
    chrome.tabs.executeScript(null, { code: script });
}