This is what I have here:
“manifest.json”
{..."permissions": [
"https:/mywebsite.com/"],"content_scripts": [{
"matches" : ["http://*/*", "https://*/*"],
"js": ["js/jquery-1.7.2.min.js", "contentScript1.js", "contentScript2.js"],
"all_frames" : true,
"run_at": "document_end"
} ]}
“contentScript1.js”
$(document).ready(function() {
$('#someDiv').load('https://mywebsite.com/index.html');}
“contentScript2.js”
function showMessage()
{alert ('Hello World!');}
“index.html”
<a href="" onclick="showMessage();"> <img src="https://mywebsite.com/images/myimage.png"></a>
What I m actually doing here is injecting a clickable picture to the code of the the page that I m visiting and I expect that by clicking the picture a “Hello World” message will be appeared. Despite the fact that the content scripts and the picture are loaded succesfully, when I click on the image the function is not called and I get the following error in the console:
Uncaught ReferenceError: showMessage is not defined
I suppose that it cannot find the function as it is looking for it in the website that I have injected the code and not in the content scripts. But why is that, I mean if I call the function within the content script when it is loaded and not by clicking the image, the message appears. Can anyone get me out of here?
You did not understand my solution to avoid conflicts does not work with your current code. Instead of using
$.noConflict, you’re wrapping your script injection function in a$().readymethod.You have to remove jQuery from the
"js"part of the manifest:And
contentScript1.jsDon’t forget to add
js/yourscript.jstoweb_accessible_resources, so that it can be used:In
js/yourscript.js, wrap your function logic in an anonymous function in conjunction with$.noConflict.$.noConflict(true)is used to avoid conflicts with scripts in the page. It restores the original value of$andjQuery.After looking at your question again, I noticed that you’re loading content through ajax:
$('#someDiv').load(...). When the script is injected, it runs in the scope of the page. That’s why your AJAX call fails: The request is blocked because of the Same origin policy.Now, we can use a different approach to fix your code. Instead of moving the logic from Content script to the page (by an injected script), we modify the page
index.html. The click event is not pre-set, but added in the content script. For example:“index.html”:
“contentscript2.js”: