Chrome extension content loads only for a split second - javascript

I'm developing a chrome extension that involves adding a column to a table, however aside from the header the changes only load for a second before they get overridden. My changes also activate after a button within the website is pressed to load the table, but the changes always only ever take place the 2nd time the button is pressed, but never the first.
manifest.json
"name": "Better Registration",
"description": "Registration Page",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"matches": ["*://*./*"],
"js": ["content.js"],
"run_at": "document_end"
}
]
}
content.js
var run = document.getElementById("search-go");
if(run){
run.addEventListener("click", load);
}
function load(){
console.log("LOAD PAGE");
var table = document.getElementById("table1");
if(table != null){
var row = table.rows[0];
var cell = row.insertCell(9);
cell.innerHTML = "PLACEMENT HEADER";
for(let i = 1; i < table.rows.length; i++){
var cell = table.rows[i].insertCell(9);
cell.innerHTML = "PLACEMENT TEXT";
}
}
}

Related

When filling a form at document_end my script clicks a button which reloads the page so it runs again. How do I stop it running?

I´m writing a small program to autofill fields with a script.
It then submits the form.
However, once the form is submitted it reloads the page and the script runs again.
Hence, it is adding the user an infinite amount of times.
Ideally I want to add a user fill diferent information and add the next for up to 100 user.
I´m not sure how to stop this infinite loop, Im assuming the script also restarts when the page resets.
I
I tried placing a function that runs my script but since my script is run when the page loads, even though the function is in a for loop it runs non stop.
Its also hard to test since infinite loops are an issue you cant really get out of without it running to many times in first place.
My Manifest code is the following:
{
"name": "Begginer",
"version": "1.0",
"manifest_version": 2,
"description": "Fill",
// "permissions": [
// "activeTab",
// "*://*/*"
// ],
"content_scripts": [
{
"matches": ["website"],
"run_at": "document_end",
"js": ["Fill.js"]
}
],
"icons":
{
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"browser_action":
{
"default_icon": "images/puppy128.png"
}
}
My JS:
// define your username and password
var Nam='Oi Macaco';
var Gen='M';
var Nbi='123';
var Ser='Servico';
var Dna='01-01-2000';
var Dab='01-01-2000';
var Cat='categorai';
var Dis='Lunda';
var Ema='email#domain.com';
var Npa='123';
var Una='OMacaco';
// Finds Each Field
var NameF = document.getElementById('nome_new');
var SexoF = document.getElementById('sexo_new');
var NbiF = document.getElementById('num_bi');
var SerF = document.getElementById('servico');
var DnfF = document.getElementById('data_nasc_func');
var DadF = document.getElementById('data_admissao');
var CatF = document.getElementById('categoria');
var DisF = document.getElementById('distrito');
var EmaF = document.getElementById('email_new');
var PasF = document.getElementById('password_new');
var UnaF = document.getElementById('unamesso_new');
// Fills the Fields
NameF.value = Nam;
SexoF.value = Gen;
NbiF.value = Nbi;
SerF.value = Ser;
DnfF.value = Dna;
DadF.value = Dab;
CatF.value = Cat;
DisF.value = Dis;
EmaF.value = Ema;
PasF.value = Npa;
UnaF.value = Una;
//Click Button
document.getElementById('Button1').click();
Everything is working, the problem is it runs an infinite number of times.
So I assume I can´t even add the Next User.
Everything is an assumption since its hard to test infinite loops, I wasnt really expecting it.
I think I should use chrome.browserAction.onClicked.addListener(function callback)
Then I should make a function that has a switch for every different user.
But that does not seem like the best way.
Help. Thx.
I solved it by inserting the following code:
Thanks to DanHarper,
Manifest
{
"name": "Inject",
"version": "0.0.1",
"manifest_version": 2,
"description": "Injecting stuff",
"background": {
"scripts": [
"background.js"
],
"persistent": true
},
"browser_action": {
"default_title": "Inject!"
},
"permissions": [
"activeTab"
]
}
Inject.js
(function() {
// define your username and password
var Nam='Oi Macaco';
var Gen='M';
var Nbi='123';
var Ser='Servico';
var Dna='01-01-2000';
var Dab='01-01-2000';
var Cat='categorai';
var Dis='Lunda';
var Ema='email#somethin';
var Npa='123';
var Una='OMacaco';
// Finds Each Field
var NameF = document.getElementById('nome_new');
var SexoF = document.getElementById('sexo_new');
var NbiF = document.getElementById('num_bi');
var SerF = document.getElementById('servico');
var DnfF = document.getElementById('data_nasc_func');
var DadF = document.getElementById('data_admissao');
var CatF = document.getElementById('categoria');
var DisF = document.getElementById('distrito');
var EmaF = document.getElementById('email_new');
var PasF = document.getElementById('password_new');
var UnaF = document.getElementById('unamesso_new');
// Fills the Fields
NameF.value = Nam;
SexoF.value = Gen;
NbiF.value = Nbi;
SerF.value = Ser;
DnfF.value = Dna;
DadF.value = Dab;
CatF.value = Cat;
DisF.value = Dis;
EmaF.value = Ema;
PasF.value = Npa;
UnaF.value = Una;
//Click Button
document.getElementById('Button1').click();
alert('inserted self... giggity');
})();
Background code:
// listen for our browserAction to be clicked
chrome.browserAction.onClicked.addListener(function (tab) {
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});
});

Chrome extension - Unexpected end of Input

I'm trying to code my first chrome extension, it's supossed to simple autosort for tabs by url name but I'm getting "Unexpected End of Input" at the end of this block of code. It only showed up after I added the listener of onClicked.
chrome.browserAction.onClicked.addListener(function apllyOrder(tabs) {
// gets reference array of sorted tabs
reference = sortTabsUrl(tabs);
console.log("Reference array loaded");
// gets amount of pinned tabs to skip them
pinned = tabsPinned(tabs);
console.log("Pinned tabs identified");
//iterates through reference array
for(var i = 0, len = reference.length; i < len; i++){
//iterates through tabs starting from first unpinned tabs
for(var x = pinned, leng = tabs.length; x < leng; x++){
//If the id matches AND reference index is different than current index than it moves the tab
if(tabs[x].id == reference[i].id && x != (i +pinned)){
// tabs is moved based on x(current index) + i(reference index)
chrome.tabs.move(tabs[x].id, i + x)
}
}
}
});
My manifest file is this:
{
"manifest_version": 2,
"name": "Tab Organizer",
"description": "Auto Organizes Tabs",
"version": "1.0",
"background": {
"scripts": ["tabOrganizer.js"],
"persistent": false
},
"permissions": [
"tabs",
"<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
I imagine I'm making a dumb mistake since I'm new at this but thanks in advance!

How can I change document elements by webExtension when user click on extension icon in toolbar?

I want to create a webExtension and I want to have icon in toolbar for this extension.
In my manifest.json file I put this code:
{
"manifest_version": 2,
"name": "test",
"version": "1.0",
"description": "test",
"icons": {
"48": "icons/icon48.png",
"96": "icons/icon96.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"activeTab",
"contextMenus"
],
"browser_action": {
"default_icon": {
"19": "button/btn19.png",
"38": "button/btn38.png"
},
"default_title": "test"
}
}
When user click on this extension icon in toolbar, I want to get elements of current page and add < a > tag in document where I want. I put this java script code in background.js file. But these code doesn't execute.
How can I fix this?
background.js :
function change() {
var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
var str = elems[i].innerHTML;
if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
var aTag = document.createElement("a");
aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
aTag.setAttribute('target', "_blank");
aTag.innerHTML = " --**CHANGES**-- ";
elems[i].appendChild(aTag);
}
}
}
browser.browserAction.onClicked.addListener(change);
Background pages do not have access to the contents of the web page.
You need to use content scripts. Content scripts are injected into the page after page load on idle
Get more information from the documentation
to add a content script to your extension you can add this to manifest.json
"content_scripts": [{
"matches": ["*://*/*"],
"js": ["contentscript.js"]
}]
and then rename background.js to contentscript.js. This way the code is always executed on each page.
Or alternatively just create contentscript.js and move the contents change() function into it
contentscript.js:
var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
var str = elems[i].innerHTML;
if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
var aTag = document.createElement("a");
aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
aTag.setAttribute('target', "_blank");
aTag.innerHTML = " --**CHANGES**-- ";
elems[i].appendChild(aTag);
}
}
then background.js will call tabs.executeScript() when browser action clicked. This way it is only called when necessary
background.js:
browser.browserAction.onClicked.addListener(function(){
browser.tabs.executeScript({file: "/contentscript.js"})
});

Create hyperlinks on certain words in Gmail message

I am working on an extension for Chrome. I wish to create hyperlinks 1) for every certain words (using RegExp), 2) automatically (before display), 3) in gMail message.
However, below codes doesn't work and gmail cannot load its message. Could you let me know why it happened and how I can fix it?
1.manifest.json
{
...
"content_scripts": [ {
"js": [ "content.js" ],
"matches": [ "<all_urls>" ],
"run_at": "document_start",
"all_frames": true
} ]
...
}
2.content.js
var doFilter = function(elem) {
//ID Moderators & URL parameters
var internalID = new RegExp(/[1-9]\d{7,8}/g);
var internalURL = 'https://mywebsite.com/go?customerId=';
//Create Hyperlinks for Internal ID
var internalMatch = elem.innerHTML.match(InternalID);
for (var i=0; i<internalMatch.length; i++) {
elem.innerHTML = elem.innerHTML.replace(internalMatch[i], '' + internalMatch[i] + '');
}
};
window.addEventListener("DOMContentLoaded", function() {
doFilter(document.body);
});

Chrome extension not working on specific websites

My chrome extension which looks for a phone number on a webpage is not working. Essentially, i expect an icon to appear besides the number. It works on other websites, but not on say google.com search results page. E.g.: https://www.google.com/#q=macy's%20redmond Do you know why?
Here is my code.
reverphonescript.js:
var hostname = document.location.hostname;
if (hostname.indexOf('xp')== -1)
{
// Initiate recursion
wpReversePhoneLookup(document.body);
function wpReversePhoneLookup(elem) { // elem must be an element node
var nodes = elem.childNodes
, i = nodes.length
, regexp = /([\(]|)\d*([\+)]|)\d*[-\.\(\ ][0-9][0-9][0-9][-\s\.\)]*(([0-9][0-9][0-9][-\s\.][0-9][0-9][0-9][0-9])|([ ][1-9][0-9][0-9][0-9][0-9][0-9][0-9])|[1-9][0-9][0-9][0-9][0-9][0-9][0-9])]*/gi
, node, phoneNode, a, result;
while (node = nodes[--i]) {
if (node.nodeType === 1) {
// Skip anchor tags, nested anchors make no sense
//if (node.nodeName.toUpperCase() !== 'A')
wpReversePhoneLookup(node);
} else if (node.nodeType === 3) {
// Please note that the regexp has NO global flag,
// and that `node.textContent` shrinks when an address is found
while (result = regexp.exec(node.textContent)) {
//console.log(result);
node = node.splitText(result.index);
node = node.splitText(result[0].length);
phoneNode = node.previousSibling
//console.log(phoneNode)
var link = "https://pro.lookup.whitepages.com/phones?number=" + result[0];
var imgURL = chrome.extension.getURL("images/rsz_wp_16.png");
var img = new Image();
img.src = imgURL;
img.className = "wpChromeExtensionImg";
img.onclick = function() {
window.open( link ,"_blank" ,"width=1000, height=650");
};
document.getElementsByClassName("wpChromeExtensionImg").src = imgURL;
//Create link
wpLink = document.createElement('a');
wpLink.href = '#';
//Append phoneNode
wpLink.appendChild(img)
var refNode = phoneNode;
refNode.parentNode.insertBefore(wpLink, refNode.nextSibling);
}
}
}
}
}
And manifest.json:
{ // Required
"manifest_version": 2,
"name": "XP",
"version": "1.0",
"description": "XP Reverse Phone Lookup. ",
"icons": { "128": "images/rsz_xp_128.png"
},
"web_accessible_resources": [
"images/*.png",
"js/reversePhoneScript.js"
],
"browser_action": {
"default_icon": {
"19": "images/rsz_wp_19.png"
},
"default_title": "XP Reverse Phone Lookup"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts" : [
{
"matches" : ["http://*/*", "https://*/*"],
"js" : ["js/reversePhoneScript.js"],
"run_at" : "document_idle", //document_end
"all_frames" : false
}
]
}
Any help will be much appreciated.
Thanks,
Kushal.
use the chrome "inspect" tool to find your icon in the page. use the ctrl-f to find your icon in the page. https://developer.chrome.com/devtools/index
some css might be moving your icon to the far left of the screen, or much simply, no z-index tag is applied to your icon so it might be hiding behind something else. http://www.w3schools.com/CSSref/pr_pos_z-index.asp

Categories