Search code examples
javascriptjquerygoogle-chrome-extensioncontent-script

Script works in console but doesn't work in chrome extension


I'm trying to write a google chrome extension to scarpe some data from an internet store (product title, description, price etc.) and put that data to a classified adds website.

I also want to download all images from the product gallery to be able to upload them to the latter website.

Because the product page contains small resolution pics I click on them in order to load a mid resolution pics and then download them using HTML5 attribute download.

Here is the script that I've wrote:

//Fing li elements with small versions of pics
var li = $('#product_card_nav li');
var li_length = li.length; 
for (i=0; i<li_length; i++) {
    //click on each small pic to load a mid resolution pic
    li.eq(i).find('a').trigger('click');
    var img = $('.b-gallery2__img img');
    //create a link to download a mid resolution pic
    var link = document.createElement('a');                  
    link.href = img.attr('src');                  
    link.download = 'MyToy.jpeg';                  
    document.body.appendChild(link);                  
    link.click();   
}

This script works fine when I copy and paste it in the chrome console. But when I try to use it in the content script of my chrome extension it always downloads only first pic several times.

What is the reason for such behaviour?


Solution

  • Content script can access the javascript in your web page. When you trigger click, nothing happend because the code that you want to run is from the web page.

    For more information - https://developer.chrome.com/extensions/content_scripts#execution-environment

    (I'm sorry about my english)