Chrome extension: get current site name - javascript

I just get started building my first Chrome extension. One functionality in my app is to get the name of the current site. For example, if the current url matches "*://*.facebook.com/", I would interpret this url and know the site name as Facebook.
How should I go about doing this?

It's not clear wheter you want to get the host name or the title of the page, but you can get both of them if you want.
Inside a content script you can do:
var site = location.hostname,
title = document.title;
alert("Site: " + site + " - Title: " + title);
If you want to do this from the background page and you don't want to use content scripts nor inject code in the tab then you can only get the host name:
var site;
chrome.tabs.query({/* some query */}, function(tabs) {
site = tabs[0].url.split("/")[2];
alert("Site: " + site);
});
If you also want to get the page title from the background page you'll need to use executeScript(). NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() instead of chrome.tabs.executeScript().
var title;
chrome.runtime.onMessage.addListener(function(message, sender, sensResponse) {
if (message.title) {
title = message.title;
alert("Title: " + title);
}
});
chrome.tabs.query({/* some query */}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {code: "chrome.runtime.sendMessage({title: document.title});"});
});
For more informations about the methods I used in the above snippets you can see these documentation links:
chrome.tabs API
chrome.tabs.query method
chrome.tabs.executeScript method (deprecated, manifest v2)
chrome.scripting.executeScript method (manifes v3)
Message passing
chrome.runtime.onMessage event
chrome.runtime.sendMessage method

Since the content script is injected into the page, you could use window.location.host in the content script itself and get the name of your site.

Related

How do I link an external js file that returns code 302

I am trying to combine Github Pages with Google Apps Script so I can have Server Side Scripting with Github Pages. I try to connect to the Google Script web app using:
<script src="https://script.google.com/macros/s/NO_LINK_FOR_YOU/dev">
</script>
(I need that /dev there, google script says nothing was returned when I don't use it.)
That is supposed to (and does) return:
return ContentService.createTextOutput("window.onload = function(){document.getElementById(\"request\").innerHTML = \"Generated: " + generateRandomNumber(10, 42) + "\";}");
Which outputs this:
window.onload = function(){document.getElementById("request").innerHTML = "Generated: 28";}
(Of course, it would not always be 28.)
When I load this into the browser, it does nothing. I looked in inspect element and it says that it's returning the code 302 (Temporarily Moved). This is usually used for redirects, and content service always makes the browser redirect "for security reasons", so this is expected.
But how can I get the browser to follow that redirect and get the script from there? Can I even do that?
In this case, a mimetype error occurs, since mimetype is not set. So please add setMimeType() as follows.
return ContentService
.createTextOutput("window.onload = function(){document.getElementById(\"request\").innerHTML = \"Generated: " + generateRandomNumber(10, 42) + "\";}")
.setMimeType(ContentService.MimeType.JAVASCRIPT);

is it possible to redirecturl without changing url

I'm creating a chrome extension that if you domain.com, it will redirect you to domain.com.ipaddress.com
Here's the main code:
chrome.webRequest.onBeforeRequest.addListener(function (details) {
var url = details.url.split("/")[2];
var url = "http://" + url + ".ipaddress.com";
return { redirectUrl: url };
}, {
urls: ['*://*/*']
}, ['blocking']);
My problem is how do i display the contents of domain.ipaddress.com without the changing the url (domain.com). Because when i visit google.com the url text changes to google.com.ipaddress.com
I know i'm bad at explaining. To understand more, im gonna express what i want using an image.
Thankfully, that's not possible.
You can't influence the address bar, it will show the actual source of the page / final redirected address.
As noted in comments, to permit otherwise would be a severe security problem.

Chrome extension and .click() loops using values from localStorage

I have made a Chrome extension to help using a small search engine in our company's intranet. That search engine is a very old webpage really convoluted, and it doesn't take parameters in the url. No chance that the original authors will assist:
The extension popup offers an input text box to type your query. Your
query is then saved in localStorage
There is a content script inserted in
the intranet page that reads the localStorage key and does a document.getElementById("textbox").value = "your query"; and then does
document.getElementById("textbox").click();
The expected result is that your search is performed. And that's all.
The problem is that the click gets performed unlimited times in an infinite loop, and I cannot see why it's repeating.
I would be grateful if you would be able to assist. This is my first Chrome extension and all what I have been learning about how to make them has been a great experience so far.
This is the relevant code:
The extension popup where you type your query
popup.html
<input type="search" id="cotext"><br>
<input type="button" value="Name Search" id="cobutton">
The attached js of the popup
popup.js
var csearch = document.getElementById("cotext");
var co = document.getElementById("cobutton");
co.addEventListener("click", function() {
localStorage["company"] = csearch.value;
window.open('url of intranet that has content script applied');
});
And now the background file to help with communication between parts:
background.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
sendResponse({data: localStorage[request.key]});
});
And finally the content script that is configured in the manifest to be injected on the url of that search engine.
incomingsearch.js
chrome.extension.sendRequest(
{method: "getLocalStorage", key: "company"},
function(response) {
var str = response.data;
if (document.getElementById("txtQSearch").value === "") {
document.getElementById("txtQSearch").value = str;
}
document.getElementById("btnQSearch").click();
});
So as I mentioned before, the code works... not just once (as it should) but many many times. Do I really have an infinite loop somewhere? I don't see it... For the moment I have disabled .click() and I have put .focus() instead, but it's a workaround. I would really like to use .click() here.
Thanks in advance!
The loop is probably caused by clicking the button even if it has a value. Try putting it inside your if. That said, you are overcomplicating it.
You can access the extension's data inside content scripts directly by replacing localstorage with the chrome.storage extension api. Add the "storage" (silent) permission to your manifest.json, like this:
"permissions": ["storage"]
Remove the message passing code in background.js. Then replace the popup button listener contents with:
chrome.storage.local.set({ "company": csearch.value }, function() {
chrome.tabs.create({ url: "whatever url" })
})
Replace the content script with:
chrome.storage.local.get("company", function(items) {
if(document.querySelector("#txtQSearch").value == "") {
document.querySelector("#txtQSearch").value = items.company
document.querySelector("#btnQSearch").click()
}
})
document.querySelector() performs the same function here as getElementById, but it is much more robust. It also has less capital letters, which makes it easier to type in my opinion.

postMessage in PhoneGap not working - iframe to parent messaging

I've build a PhoneGap app which which makes use of an iframe which is bundled with the app and I'm am trying to pass e message from the iframe to the parent which doesn't seem to be working when I run the app on an actual iPad; however it works fine when I run the app in the browser on the same device.
Here is the code I'm using inside the iframe to send a message, note that I'm using HammerJS to capture some events:
var domain = 'http://' + document.domain;
$('body').hammer().on("swipe", "", function(event) {
var message = event.gesture.direction;
parent.postMessage(message,domain); //send the message and target URI
});
and the code I'm using to get the message:
window.addEventListener('message',function(event) {
alert(event.data);
},false);
And the answer is to use "file://" as the domain name so the code will look like this:
var domain = 'file://';
$('body').hammer().on("swipe", "", function(event) {
var message = event.gesture.direction;
parent.postMessage(message,domain); //send the message and target URI
});
Try with using
var domain = '*';
Normally this should be because of cross domain problem, see more here
You will need to use:
parent.postMessage(message,"*");
Since phonegap/cordova pages are served at "file://" and according to https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
"...posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future."

Firefox Addon won't open new tab with url

I tried this code:
var contextMenu = require("context-menu");
var menuItem = contextMenu.Item({
label: "Test name",
contentScript: 'self.on("click", function () {' +
' window.open("options.html", "_blank");' +
'});'
});
But when I click on the new Context menu item, I get the following error:
Security Error: Content at "le Site" may not load or link to chrome://browser/content/options.html.
Which permissions do I have to give of get?
It seems that the relative address is resolved incorrectly in case of a content script - as a result you are attempting to open chrome://browser/content/options.html in a window which is correctly forbidden. Simply specify the full address and things should work:
' window.open("http://example.com/options.html", "_blank");' +

Categories

Resources