Chrome extension: load different content scripts - javascript

I want to load a different content script depending on the page and tab that is currently selected. Right now, I have three content scripts. I want to use two of them for one page and the third one for another page.
Belonging to page 1:
content_script.js
load_content_script.js
Belonging to page2:
newtab_content_script.js
right now my manifest looks like this
{
"name": "A plugin for AdData express. Generate an instant excel document from the brands you check mark.",
"version": "1.0",
"background_page": "background.html",
"permissions": [
"cookies",
"tabs",
"http://*/*", "https://", "*", "http://*/*", "https://*/*",
"http://www.addataexpress.com", "http://www.addataexpress.com/*"
],
"content_scripts": [
{
"matches": ["<all_urls>","http://*/*","https://*/*"],
"js": ["load_content_script.js", "content_script.js", "newtab_content_script.js", "jquery.min.js", "json.js"]
}
],
"browser_action": {
"name": "AdData Express Plugin",
"default_icon": "icon.png",
"js": "jquery.min.js",
"popup": "popup.html"
}
}
how would I structure this in the manifest or elsewhere?

Just in the interest of completeness, the way you'd do this from the manifest is to have as many matches blocks under "content_scripts" as needed:
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mygooglestyles.css"],
"js": ["jquery.js", "mygooglescript.js"]
},
{
"matches": ["http://www.yahoo.com/*"],
"css": ["myyahoostyles.css"],
"js": ["jquery.js", "myyahooscript.js"]
}
],

Rather than using content scripts that are bound to URL expressions specified in the manifest, you should use executeScript, which lets you programmatically decide when to inject a JS snippet or file:
// background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// there are other status stages you may prefer to inject after
if (changeInfo.status === "complete") {
const url = new URL(tab.url);
if (url.hostname === "www.stackoverflow.com") {
// this is the line which injects the script
chrome.tabs.executeScript(tabId, {file: "content_script.js"});
}
}
});
Make sure to add tabs permission to manifest.json:
{
// ...settings omitted...
"permissions": [
"tabs", // add me
]
}

you should use Programmatic injection
chrome.tabs.executeScript(null, {file: "content_script.js"});

Related

Chrome Extensions Auto Clicker

I am making a chrome extension it will get me to certain page by autoclicking. Since it goes from page to page. I am not able to get past after the first page. I am not able to do when the second page loads after first click
manifest.json
{
"manifest_version": 2,
"name": "AutoClick",
"description": "This autoclicks",
"version": "1.1",
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"content_scripts": [{
"matches": ["*://*.blogger.com/*"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}],
"permissions": [
"activeTab",
"tabs",
"*://*.blogger.com/*"
]
}
background.js
chrome.tabs.create
chrome.browserAction.onClicked.addListener(function (tab) {
var newURL = "https://draft.blogger.com/blog/posts/3778735982367012067";
chrome.tabs.create({ url: newURL });
chrome.tabs.executeScript({ file: "content.js" });
});
content.js
function createpost(){
document.querySelector('.CwaK9').click()
}
function video1(){
document.querySelector('.vde74d').click()
}
if (window.location.href == "https://draft.blogger.com/blog/posts/3778735982367012067") {
createpost()
newFunction()
}
function newFunction() {
if (window.location.href.match('https://draft.blogger.com/blog/posts/3778735982367012067/')) {
video1();
}
}
using match because it add random ID to end of the URL after first click.
It works fine during first click but when the next page loads it don't.

Chrome extension - collect HTMLcollection from file

I'm creating a in house chrome extension which collects data from a webpage (broke links etc for SEO) but i'm having issues. My original script injected the js onpage which was great as it had a box and collected what was needed, the only issue was it wasn't a Popup box so it didn't close correctly etc. I now have a script which on load pulls all dom data and a script which display and manipulates the data. The only issue I have is collecting the data from the file.
Manifest.json
{
"name": "",
"version": "1.2.4",
"manifest_version": 2,
"description": "",
"homepage_url": "",
"background": {
"scripts": [
"background.js",
"Returndocdata.js"
],
"persistent": true
},
"browser_action": {
"default_title": ""
},
"icons": { "16": "icon16.png" },
"permissions": [
"https://*/*",
"http://*/*",
"tabs"
],
"content_scripts": [
{
"matches": ["*://*/*"],
"run_at": "document_start",
"js": ["Returndocdata.js"]
}
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab, info) {
chrome.tabs.executeScript({file: 'Returndocdata.js'});
});
chrome.browserAction.onClicked.addListener(function(tab, info) {
chrome.browserAction.setPopup({popup: "inject.html"})
});
inject.html
<div id = "ContactDetails">
<input type="text" name="lname">
</div>
<script src="inject.js"></script>
Returndocdata.js
var all = document.getElementsByTagName("*");
console.log(all);
inject.js
this is the file that needs the returndocdata.js data, i need a way to grab that data and pull it into this keeping the formatting (the htmlcollection)
This works if I include the script in the header but due to it not being ran on the web page itself it only returns data from the popup extension.
It's most likely a small thing
Ta

Screenshot using chrome.tabs.captureVisibleTab

I'm trying to capture the visible area of a page using chrome.tabs.captureVisibleTab. Here is the code that makes the call:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.name == 'screenshot') {
chrome.tabs.captureVisibleTab(null, null, function(dataUrl) {
sendResponse({ screenshotUrl: dataUrl });
});
}
});
But when I try to capture the tab I get this error:
Unchecked runtime.lastError while running tabs.captureVisibleTab: The 'activeTab' permission is not in effect because this extension has not been in invoked.
Here is my manifest file:
{
"manifest_version": 2,
"name": "Empathy",
"version": "0.1",
"description": "Simulate accessibility issues for websites.",
"browser_action": {
"default_icon": "empathy19.png",
"default_title": "Empathy!"
},
"permissions": [
"activeTab",
"contextMenus",
"desktopCapture",
"tabCapture",
"tts" // Text-to-speech
],
"background": {
"scripts": [
"boot.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"src/helpers.js",
"src/colorblindness.js",
"lib/colorvision.js",
"lib/html2canvas.js"
]
}
]
}
I have active tab permissions
The call is being made from a background script
I'm matching <all_urls>
Why do I get that error?
There are things that talk about <all_urls> as something to match, but what I was missing was the <all_urls> permission. After I added the permission, it worked.

Using JQuery in a content script

I am trying to use JQuery in my content script but The chrome console spits this out "Uncaught ReferenceError: $ is not defined ". I can successfully use JQuery in my background script so I'm not exactly sure whats up.
Here's the manifest file:
{
"name": "Something",
"version": "1.0",
"description": "SOmething",
"background": {
"scripts": ["background.js", "jquery.js"],
"persistent": true
},
"browser_action": {
"default_icon": "favicon.png",
"default_popup": "popup.html"
},
"permissions": [
"declarativeContent",
"http://localhost/",
"http://*/*",
"https://localhost/",
"https://*/*",
"tabs"
],
"icons": {
"48": "icon-48p.png"
},
"content_scripts": [{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["content.js", "jquery.js"]
}],
"web_accessible_resources": ["button.PNG", "jquery.js"],
"manifest_version": 2
}
Here's the content script:
var btn = document.createElement("input");
btn.id = "btn";
btn.type = "image";
btn.setAttribute("src", chrome.extension.getURL("button.PNG"));
btn.onclick = function() {
alert("Currently under development");
};
btn.className = "";
if (window.location.href.indexOf("mysite") > -1) {
$('#pageContainer').append('<ol><li>CATS</li><ol>'); //Fails here
}
if (window.location.href.indexOf("myother") > -1) {
document.getElementById("maindiv").appendChild(btn); //works
}
Edit: JQuery is in the project and it does work in background.js. The question is how do I get it working within my content script? I've specified in the manifest that I want jquery injected along with content.js.
Make jQuery the first content script listed in thecontent_scripts -> js array. Like:
"content_scripts": [{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["jquery.js", "content.js"]
}],
Your content script is trying to access jquery before it's loaded. The way your manifest is set up now, jQuery still should be loaded however. To verify this, type something like window.jQuery into the console on the content script page and make sure that it is defined.
As berrberr pointed out, you have to load jquery before your content.js script as follows
"js": ["jquery.js","content.js"]
or you can achieve the same in Pure JS using appendChild().
Also a note: If you are manipulating DOM elements, try injecting your script at document_end

Selectively include javascript file dependent on website

I'm trying to build a Chrome Extension that will work with two websites, we'll call them website1.com and website2.com. Depending on what website we are on I would like to include a different JS file that will store all the logic (In this example I have called it code-for-website-1.js (there would also be another JS for website2.com).
I'm having a problem figuring out how I can only include code-for-website-1.js when I am on website1.com and code-for-website-2.js when I am on code-for-website-2.js.
Here is my manifest:
{
"name": "My Chrome Extension",
"version": "1.0",
"description": "Extension description",
"manifest_version": 2,
"permissions": ["tabs", "http://www.website1.com", "http://www.website2.com"],
"content_scripts": [
{
"matches": ["http://www.website1.com"],
"js": ["jquery.js", "code-for-website-1.js"]
}
]
}
I tried to use one controller.js that would use the following command:
if (onWebsite1 == true){
chrome.tabs.executeScript(null, { file: "code-for-website-1.js" });
} else {
chrome.tabs.executeScript(null, { file: "code-for-website-2.js" });
}
With this I just get the error:
Uncaught TypeError: Cannot call method 'executeScript' of undefined
in the manifest according to the documentation you can add multiple objects to the content_script array
example
"content_scripts": [
{
"matches": ["http://www.website1.com/*"],
"js": ["script_for_website1.js"]
},
{
"matches":["http://www.website2.com/*"],
"js":["script_for_website2.js"]
}
]

Categories

Resources