简体   繁体   中英

Changing src of img using jquery

I know this question has been asked before, but my code still isn't working and I don't know why; I'm trying to make a chrome extension that changes images of class 'profilePic img' with a click

This is my code so far: background.js:

chrome.browserAction.onClicked.addListener(function (tab) {
    if (tab.url.indexOf("https://www.facebook.com") != -1) {
        chrome.tabs.executeScript(tab.id, {
            "file": "contentscript.js"
        }, function () { 
            console.log("Script Executed"); 
        });
    }
});

contentscript.js:

alert("alert");
$(document).ready(function() {
$(document).find('.profilePic img').attr('src', 'second.jpeg')    
});

manifest.json

{
  "name": "stuff",
  "version": "0.0.1",
  "manifest_version": 2,

  // Recommended
  "description": "replaces fb profile pictures",
    "web_accessible_resources": [
    "second.jpeg"
  ],
 "background":{
            "scripts":["background.js"],
            "page": "background.html"
        },
         "permissions":["https://www.facebook.com/*"],
  "content_scripts": [
        {
            "matches":["http://www.facebook.com/*"],
            "js":["jquery-2.1.4.min.js","background.js","contentscript.js"],
            "all_frames": true,
            "run_at": "document_start"
        }
    ],
    "browser_action": {
  "default_icon": "icon.png",
  "default_title": "testing"
}
}

alert pops up just fine, but nothing is changed...I have jquery already included in my manifest edit: I think this is a problem with uploading jquery, as the console log error is '$ is not defined'. Sorry! Complete beginner here :(

This is most likely occurring because the profilePic class is used on an img tag. Facebook profile pictures use the class profilePic with a selector , which is probably what's tripping you up. If it looked something like this your code in its current form would work, it would seek the profilePic class and then find any img tags within it, replacing the src attribute.

<div class="profilePic">
<img src="https://www.google.com/images/srpr/logo11w.png">
</div>

However because you have the profilePic class on the image itself you'll need to refactor your jQuery so it looks like this

$(".profilePic").attr("src","second.jpeg");

You could also do something like this, I'm not entirely sure how Facebook is put together usually, but this was taken from my page.

$("#fbPageFinchProfilePic img").attr("src","second.jpeg");

You can test this out using this JSFiddle: http://jsfiddle.net/u8zr55vz/1/

I hope that helps! Be sure to read up on the jQuery .attr() here for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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