Scanning URL All the time - Chrome Extension - google-chrome

I need to develop extension, where everytime i write url and in chrome and press enter. My url is first scanned, if it matches some pattern say like if the url patter has youtube in it, redirect it to facebook
This should be done automatically - not everytime i have press the icon of (chrome extension), meaning this script or piece of code will not be running on-click event, rather once installed it will always scan the url entered and do the require change and reload the tab.
Please help me out. I reach this far
<html>
<script>
function getname()
{
chrome.tabs.getSelected( null , function(tab) {
var rawurl="http://www.youtube.com/watch?";
var newurl= "http://www.youtube.com/watch?feature=player_leanback&"
if (0 === tab.url.indexOf(rawurl))
chrome.tabs.update(tab.id, {url: tab.url.replace(rawurl,newurl)});
});
}
</script>
<body onload="getname();">
</body>
</html>
I achieve this but you onload event in J-Script - is there anyway I can do this all the time without using onload() as onload require explicit click all the time.

Rewriting the code
<html>
<script>
function getname()
{
chrome.tabs.getSelected( null , function(tab) {
var rawurl="http://www.youtube.com/watch?";
var newurl= "http://www.youtube.com/watch?feature=player_leanback&"
if (0 === tab.url.indexOf(rawurl))
chrome.tabs.update(tab.id, {url: tab.url.replace(rawurl,newurl)});
});
}
</script>
<body onload="getname();">
</body>
</html>

You should consider APIs such like chrome.webRequest or chrome.webNavigation.
Besides, I believe this extension has implemented everything you mentioned.

Related

URL bar not updated in Chrome after Backbone routing

I have a Backbone application which, at one point, opens a new tab in the browser. After the execution in the new tab is complete a javascript will be triggered (in that new tab) to trigger routing in the opener window. Javascript code looks like this:
window.onunload = window.onbeforeunload = function(e){
opener.router.navigate("start",{trigger: true});
};
window.close();
This works great, the 'start' route is executed and the correct result is shown in all browsers (including Chrome). But in Chrome, the url bar is not updated with the new url (eg. ../something#start), instead the original url for the opening window remains in the address bar.
In IE and Firefox the url bar shows the correct url. Is there some way to achieve this behaviour in Chrome also?
Any input appreciated!
Instead of trying to make a call to the router directly from the tab that's about to be closed, have you tried triggering a Backbone event (which the "opener window" would be listening to) instead?
So change:
window.onunload = window.onbeforeunload = function(e){
opener.router.navigate("start",{trigger: true});
};
window.close();
to:
window.onunload = window.onbeforeunload = function(e){
Backbone.trigger('routeChange');
};
window.close();
And include a listener to the routeChange event in the "opener window's" view with a callback function which executes router.navigate():
opener.listenTo(Backbone, 'routeChange', function(e) {
opener.router.navigate('start',{trigger: true});
});
Let me know if that helps.

Chrome Extension: Insert a clickable image using a content script

I know hat it is possible, but I am not quite sure how to do it the 'right' way, as to ensure there are no conflicts.
I came across this question: Cannot call functions to content scripts by clicking on image . But it is so convoluted with random comments that it's hard to understand what the corrected way was.
Use case:
Html pages have a div on the page where they expect anyone using the Chrome extension to inject a picture. When users click on he picture, I want to somehow notify an event script. So I know I need to register a listener so the code inserted messages the event script.
Can I get some indication on what code to inject through the content script? I saw that sometimes injecting jquery directly is advised.
I am trying to avoid having the html page to post a message to itself so it can be intercepted. Thanks
With the help of Jquery something like this would capture the image onclick event and allow you to pass a message to a background page in the Chrome Extension:
$("img").click(function(){
var imageSrc = $(this).attr("src");
//Post to a background page in the Chrome Extension
chrome.extension.sendMessage({ cmd: "postImage", data: { imgSrc: imageSrc } }, function (response) {
return response;
});
});
Then in your background.js create a listener for the message:
chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.cmd == "postImage") {
var imageSrc = request.data.imgSrc;
}
});

JSON and passing a URL value as a parameter - Chrome Extension

Ok, this is my final tango with this. Below I've listed the code. I'm able to get the value of the url and display it on screen for the current (active tab) in Google Chrome. Now all I have to do is pass that value as a parameter in the URL via JSON. My processing file resides on a our remote server - in php. Everything I've done with respect to this has worked to perfection. However, any attempts to pass the current url or any url as one of the parameters - e.g. ?format=json&url=http://something.com&callback=? - results in nothing. I'm not sure if what I'm doing is wrong or if it is even possible. The important thing to note is that all we are looking to do is pass the url to a remote server for storage, processing etc and send back results. I have everything working but I just can't seem to get the url to pass as a parameter.
<html>
<head>
<title>API JSON Test</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var timeService =
"http://api.ulore.com/api2.php?key=abce&url="+tab.url+"&format=json&callback=?";
$.getJSON(timeService, function(data) {
$('#showdata').html("<p>url_results="+data.post.url+"</p>");
});
});
</script>
<div id="showdata"></div>
</head>
<body>
</body>
</html>
Again, all the JSON works fine when I'm testing other code. Even if I put in a NON-URL value as a parameter for url=..... it throws the appropriate error. However, it will not accept a URL for some reason.
Any feedback will be greatly appreciated.
Thanks,
Ethan-Anthony
Try encoding and decoding the url.
http://www.w3schools.com/tags/ref_urlencode.asp
http://php.net/manual/en/function.rawurlencode.php
http://phpjs.org/functions/rawurlencode:501

chrome extension API for refreshing the page

Is there an API to programmatically refresh the current tab from inside a browser action button? I have background page configured, which attaches a listener via:
chrome.browserAction.onClicked.addListener(function(tab) { ... });
So the callback function retrieves a reference to the tab that it was clicked from, but I don't see an API anywhere to refresh/reload that tab.
I think what you're looking for is:
chrome.tabs.reload(integer tabId, object reloadProperties, function callback)
Check out tabs API() documentation for more information.
The API for chrome.tabs.getSelected(), which the accepted answer uses, has been deprecated. You should instead get the current tab and reload it using something like the following:
chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, {code: code});
});
Or perhaps:
chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs) {
chrome.tabs.reload(arrayOfTabs[0].id);
});
I had no real luck with the second version, though other answers seem to suggest it should work. The API seems to suggest that, too.
I recommend using chrome.tabs.executeScript to inject javascript that calls window.location.reload() into the current tab. Something like:
chrome.tabs.getSelected(null, function(tab) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(tab.id, {code: code});
});
Reference here
More specifically:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.reload(tab.id);
});
You can also use this:
chrome.tabs.reload(function(){});
reload function params: integer tabId, object reloadProperties,
function callback
Reference: http://developer.chrome.com/extensions/tabs.html#method-reload
if you want to reload all the tabs which have loaded completely and are active in their window
chrome.tabs.query({status:'complete'}, (tabs)=>{
tabs.forEach((tab)=>{
if(tab.url){
chrome.tabs.update(tab.id,{url: tab.url});
}
});
});
you can change the parameter object to fetch only active tabs as {status:'complete', active: true} refer to query api of chrome extensions
Reason for not using chrome.tabs.reload :
If the tab properties especially the tab.url have not changed, tab does not reload. If you want to force reload every time, it is better to update the tab URL with its own tab.url which sends the event of the change in property and tab automatically reloads.

Open a "Help" page after Chrome extension is installed first time

I am new to Chrome extension. I have a question about how to make the extension to open a "Help" page automatically after installation. Currently, I am able to check whether the extension is running the first time or not by saving a value into localStorage. But this checking is only carried out when using click the icon on the tool bar. Just wondering if there is a way that likes FF extension which uses the javascript in to open a help page after the installation. Thanks.
Edit:
Thanks for the answer from davgothic. I have solved this problem.
I have another question about the popup. My extension checks the url of current tab,
if OK(url){
//open a tab and do something
}
else{
//display popup
}
Is it possible to show the popup in this way?
Check this updated and most reliable solution provided by Chrome: chrome.runtime Event
chrome.runtime.onInstalled.addListener(function (object) {
let externalUrl = "http://yoursite.com/";
let internalUrl = chrome.runtime.getURL("views/onboarding.html");
if (object.reason === chrome.runtime.OnInstalledReason.INSTALL) {
chrome.tabs.create({ url: externalUrl }, function (tab) {
console.log("New tab launched with http://yoursite.com/");
});
}
});
Add this to your background.js I mean the the page you defined on manifest like following,
....
"background": {
"scripts": ["background.js"],
"persistent": false
}
...
UPDATE: This method is no longer recommended. Please see Nuhil's more recent answer below.
I believe what you need to do is put something like this into a script in the <head> section of your extension's background page, e.g. background.html
function install_notice() {
if (localStorage.getItem('install_time'))
return;
var now = new Date().getTime();
localStorage.setItem('install_time', now);
chrome.tabs.create({url: "installed.html"});
}
install_notice();
As of now (Aug 2022) the right way to execute code on first install or update of an extension using Manifest V3 is by using the runtime.onInstalled event.
This event is documented here: https://developer.chrome.com/extensions/runtime#event-onInstalled
There is one example for this exact case in the docs now:
https://developer.chrome.com/docs/extensions/reference/tabs/#opening-an-extension-page-in-a-new-tab
Note: This example above is wrong as the callback function parameter is Object with the key reason and not reason directly.
And another example here (this one is correct but does not open a tab):
https://developer.chrome.com/docs/extensions/reference/runtime/#example-uninstall-url
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
// Code to be executed on first install
// eg. open a tab with a url
chrome.tabs.create({
url: "https://google.com"
});
} else if (details.reason === chrome.runtime.OnInstalledReason.UPDATE) {
// When extension is updated
} else if (details.reason === chrome.runtime.OnInstalledReason.CHROME_UPDATE) {
// When browser is updated
} else if (details.reason === chrome.runtime.OnInstalledReason.SHARED_MODULE_UPDATE) {
// When a shared module is updated
}
});
This code can be added to a background service worker: https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/
It would be better to place a "version" number so you can know when an extension is updated or installed.
It has been answered here:
Detect Chrome extension first run / update
All you need to do is adding the snippet below to your background.js file
chrome.runtime.onInstalled.addListener(function (object) {
chrome.tabs.create({url: `chrome-extension://${chrome.runtime.id}/options.html`}, function (tab) {
console.log("options page opened");
});
});