Hello,
can you recommend me some JS (or JQuerry) code, that would find all “a” tags which contain any number text, e.g.
3030
and replace it for title?
hi
So every link (on a page) with a visible number would be replaced for text.
[...document.querySelectorAll('a')]
.filter(node => node.textContent.match('^[0-9]+$'))
.forEach(node => node.textContent = 'hi')
Thanks for tip. I am having this code:
function detectUrl(){
$('a').each(
function() {
var value = $(this).text();
console.log(value);
}
)
}
chrome.commands.onCommand.addListener(function(command) {
detectUrl();
});
But when I run it I see nothing in the console. When I add a breakpoint to the “each” then it jumps there. When I add another break point to the anonymous function then the debugger does not jump into it.
That would suggest there’s nothing to select. Given that you have a commands listener in the same code block, I have to assume this is in the background page? If so, as the name says, the background page is its own page with its own DOM. To get the links in the current tab, you’d want to use tabs.execScript
or a content script declared in the manifest.
I found the problem. Because I am using the command, I must to add the code to the content page. It is a bit more complicated, but I will find out how to fix it.
Now I have finished sendMessage from background script so I am working on the listener on the content script.
Should I see content script in the the “remote” debugger? Because I see only background scripts.
my manifest:
{
"name": "Sample Commands Extension",
"description": "Press Ctrl+Shift+U to send an event (Command+Shift+U on a Mac).",
"homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/commands",
"manifest_version": 2,
"version": "2.0",
"background": {
"scripts": [
"jquery-3.0.0.js",
"background_scripts/namespace.js",
"background_scripts/event_handlers.js",
"background_scripts/background.js"
]
},
"applications": {
"gecko": {
"id": "commands@mozilla.org",
"strict_min_version": "48.0a1"
}
},
"commands": {
"replace_url_text_title": {
"suggested_key": {
"default": "Ctrl+Shift+U"
},
"description": "Send a 'toggle-feature' event to the extension"
}
},
"content_scripts": [
{
"matches": ["*://biblehub.com/*"],
"js": [
"jquery-3.0.0.js",
"content_scripts/addListeners.js",
"content_scripts/content_script.js"
],
"persistent": false
}
]
}
No, they’re in the page specific tools: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging#Debugging_content_scripts
I got it
$('a').
each(
function() {
/*
console.log((this).textContent);
console.log(
(this).textContent.match('^[0-9]+$')
);
*/
if ( (this).textContent.match('^[0-9]+$') != null )
{
var text = $(this).text();
var title = $(this).attr('title');
$(this).text(title);
$(this).attr('title', text);
// console.log(text);
// console.log(title);
}
} // END CLOSURE
)