简体   繁体   English

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

[英]chrome.tabs.executeScript : Doesn't work when I tried to insert an image into specific website

I was trying to insert an image into Amazon.com 我试图将图像插入Amazon.com

Firstly, I verified that following code works fine in chrome console 首先,我验证了以下代码在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)

However, When I assembled this code into chrome extension format, it seems that it didn't work any more. 但是,当我将此代码组合成chrome扩展格式时,似乎它不再起作用了。 I added "tabs","","activeTab" permissions in manifest.json and the following code is background.js 我在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();
});

The executeScript function is similar to the eval function, in that it accepts a string of code which it executes. executeScript函数类似于eval函数,因为它接受它执行的一串代码。 You are attempting to pass the results of the insertImage function (which is null). 您正在尝试传递insertImage函数的结果(为null)。 For the script to work, you must inject all the relevant JS code as a string: 要使脚本生效,必须将所有相关的JS代码作为字符串注入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM