Chrome extension; open a link from popup.html in a new tab - google-chrome

I'm doing a Chrome extension and I got helped in this post here.
My problem now is how to open a new tab of chrome that has as URL the link I clicked in the popup.html. I tried to do like someone suggested in their answers in other similar question like setting <a>'s attribute target to _blank but the only result is that chrome does open a new tab but in the new tab is my popup.html.
Any idea how to solve this?
Thanks.

You should use chrome.tabs module to manually open the desired link in a new tab. Try using this jQuery snippet in your popup.html:
$(document).ready(function(){
$('body').on('click', 'a', function(){
chrome.tabs.create({url: $(this).attr('href')});
return false;
});
});

See my comment https://stackoverflow.com/a/17732609/1340178
I had the same issue and this was my approach:
Create the popup.html with link (and the links are not working when clicked as Chrome block them).
Create popup.js and link it in the page: <script src="popup.js" ></script>
Add the following code to popup.js:
document.addEventListener('DOMContentLoaded', function () {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
});
That's all, links should work after that.

If you don't want to use JQuery, insert this into your popup.js and it will make all your links open in a new tab when clicked
Remember to declarer the "tabs" permission in the manifest.json
window.addEventListener('click',function(e){
if(e.target.href!==undefined){
chrome.tabs.create({url:e.target.href})
}
})

The other answers work. For completeness, another way is to just add target="_blank"
Or if you have want to "manually" add particular links, here's a way (based on the other answers already here):
popup.html
<a id="index_link">My text</a>.
popup.js
document.addEventListener('DOMContentLoaded', () => {
var y = document.getElementById("index_link");
y.addEventListener("click", openIndex);
});
function openIndex() {
chrome.tabs.create({active: true, url: "http://my_url"});
}

A bit more concise and actual syntax in 2020:
document.addEventListener('DOMContentLoaded', () => {
const links = document.querySelectorAll("a");
links.forEach(link => {
const location = link.getAttribute('href');
link.addEventListener('click', () => chrome.tabs.create({active: true, url: location}));
});
});

A bit more concise version in modern JS:
document.addEventListener('DOMContentLoaded', function () {
for (const anchor of document.getElementsByTagName('a')) {
anchor.onclick = () => {
chrome.tabs.create({active: true, url: anchor.href});
};
};
});

I had the same problem. Looked like Konrad's solution would worked, but it opened multiple tabs at once. This happened only after first extension install. So I changed it to
if (e.target.classList.contains("a-link")) {
chrome.tabs.create({url: $(e.target).attr('href')});
return false;
}
and all is working as expected.

Send tab url to share blog in new tab:
// popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs){
var url = tabs[0].url;
var title = tabs[0].title;
document.getElementById('linkQZone').onclick = function () {
var url1 = 'https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + url + '&title=' + title + '&desc=&summary=&site=';
chrome.tabs.create({active: true, url: url1});
};
document.getElementById('linkQQ').onclick = function () {
var url1 = 'https://connect.qq.com/widget/shareqq/index.html?url=' + url + '&title=' + title + '&desc=&summary=&site=';
chrome.tabs.create({active: true, url: url1});
};
});

open with ctrl-click or middle-click
$('body').on('click auxclick', 'a', e => {
if (e.ctrlKey || e.button == 1) {
e.preventDefault();
chrome.tabs.create({ url: e.currentTarget.href, selected: false});
}
});

Related

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

How to get webstore URL passed to extension despite "webstore cannot be scripted by extensions"

After extensive searching I discovered Rob's answer: https://stackoverflow.com/a/11614440/7907844 that "webstore cannot be scripted by extensions".
I only want to extract the URL and pass it to the extension. Is there no way to achieve this?
Could I query all opened tabs from background script, and keep the active tab URL in a variable accessible to extension?
I ended up implementing background script that saves currently active tab URL in a variable that I access from within a popup.js because webstore doesn't allow us to run content scripts there. chrome.extension.getBackgroundPage() inside popup.js only worked when I used var currentUrl.
var currentUrl;
var activeTabId;
chrome.tabs.onUpdated.addListener(
function (tabId, changeInfo, tab) {
if (changeInfo.status === "complete") {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
let activeTab = tabs[0];
currentUrl = activeTab.url;
activeTabId = activeTab.id;
if(currentUrl.includes("chrome.google.com/webstore/detail")) {
chrome.pageAction.show(activeTab.id);
} else {
chrome.pageAction.hide(activeTab.id);
}
console.log("page loaded: ", currentUrl);
});
}
});
chrome.tabs.onActivated.addListener(function (object) {
activeTabId = object.tabId;
chrome.tabs.get(activeTabId, function(tab){
currentUrl = tab.url;
if(tab.url.includes("chrome.google.com/webstore/detail")) {
chrome.pageAction.show(object.tabId);
} else {
chrome.pageAction.hide(object.tabId);
}
console.log("loaded tab selected: ", tab.url);
})
});

MooTools event not triggering in IE9 (only after refresh)

I changed the entire question because I didn't provide enough info's at the first run: thanks goes to #Sergio.
There are alot of things not working in IE.
When I do addEvent('domReady').... It's even more bad(it doesn't gets executed but if I refresh the page... it works).
Is there a proper way to handle that IE stuff in MooTools?
note:
working on every browser on the whole planet except IE*
edit: added the complete source code of ajax cart.
This code it correct, it's just for understanding purpose only:
ajax_cart.js
var AjaxCart = new Class({
Implements: Options,
cartDiv: null,
options: {
elem_id: 'shopping-cart-icon',
event: 'mouseenter',
url: 'changed_url_but_it's_correct='+(new Date().getTime())
},
var AjaxCart = new Class({
Implements: Options,
cartDiv: null,
options: {
elem_id: 'shopping-cart-icon',
event: 'mouseenter',
url: '/changed_url_but_it's_correct='+(new Date().getTime())
},
var AjaxCart = new Class({
Implements: Options,
cartDiv: null,
options: {
elem_id: 'shopping-cart-icon',
event: 'mouseenter',
url: '/changed_url_but_it's_correct'+(new Date().getTime())
},
initialize: function() {
var cart = this;
this.elem = $(this.options.elem_id);
if (this.elem) {
this.elem.addEvent(this.options.event, function() {
cart.viewCart();
});
}
},
getCart: function() {
var cart = this;
var myHTMLRequest = new Request.HTML({
url: cart.options.url,
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
//console.log(responseHTML);
if (!cart.cartDiv) {
cart.cartDiv = new Element('div', {'class':'ajax-cart'});
cart.cartDiv.fade('hide');
cart.cartDiv.inject(cart.elem);
cart.cartDiv.addEvent('mouseleave',function() {
this.fade('out');
});
}
cart.cartDiv.innerHTML= responseHTML;
cart.cartDiv.fade('in');
},
onFailure: function(xhr) {
console.log(xhr.responseText);
}
}).get();
},
viewCart: function() {
if (this.cartDiv) {
this.cartDiv.fade('in');
} else {
this.getCart();
}
}
});
This code works on every browser except IE, only after refreshing the page, it works.
in index.html
if(Browser.ie) {
var ajaxCart;
window.addEvent('load', function() {
ajaxCart = new AjaxCart({'elem_id':'shopping-cart-icon'});
});
} else {
var ajaxCart;
window.addEvent('load', function() {
ajaxCart = new AjaxCart({'elem_id':'shopping-cart-icon'});
});
}
In some versions of Internet Explorer (ie. IE6) a script tag might be executed twice if the content-type meta-tag declaration is put after a script tag.
The content-type should always be declared before any script tags.
See here http://mootools.net/docs/core/Utilities/DOMReady
I guess there is no solution so I had to find a workaround for this.
What I did:
Since my problems were solved by refreshing the page, I did this in meta tag.
<meta http-equiv="Expires" content="-1" />
It might help someone else, when it comes up to fixing IE refreshing bugs.

How to include a link in the HTML5 notification?

I would like to be able to set a link/permalink to each notification, so when user clicks on it; then he is taken to the permalink location,
I've seen this answer which has a solution that's a little bit different because static link is used,
I would like to, somehow:
var noti = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
'http://mycustom.dynamic.link.com/' /* invented code */
)
noti.onclose = function(){ alert(':(') };
noti.onclick = function(){
window.location.href = $(this).url; /* invented code */
};
noti.show();
Any chance? (I really don't like the static html file solution... I would like to keep this syntax)
How about something like this?
var createNotificationWithLink = function(image, title, content, link) {
var notification = window.webkitNotifications.createNotification(image, title, content);
notification.onclose = function() {
alert(':(');
};
notification.onclick = function() {
window.location.href = link;
};
return notification;
};
Now you can call createNotificationWithLink whenever you want to create a notification:
var noti = createNotificationWithLink(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
'http://mycustom.dynamic.link.com/'
);
noti.show();
You can also move noti.show(); into the createNotificationWithLink function if you like (notification.show();). I don't know if you want the notification to be shown automatically when you create it...
You can pass a data property that you can read from within the onclick event handler as e.target.data.
var notification = new window.Notification("Hello!",
{
body: "Hello world!",
data: "https://www.example.com/?id=" + 123
});
notification.onclick = function(e) {
window.location.href = e.target.data;
}
noti.onclick = function() {
window.open("http://www.stackoverflow.com")
};
More on how to use window.open: http://www.w3schools.com/jsref/met_win_open.asp4
HTML5 Notification Resource: http://www.html5rocks.com/en/tutorials/notifications/quick/ (If this doesn't answer you're question)
For Each one you could have:
var noti1 = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification',
'HTML5 Notification content...',
var noti2 = window.webkitNotifications.createNotification(
'http://funcook.com/img/favicon.png',
'HTML5 Notification #2',
'HTML5 Notification #2 content...',
etc
and then
noti1.onclick = function() {
window.open("http://www.stackoverflow.com")
};
noti2.onclick = function() {
window.open("http://www.example.com")
};
hope that helps :)
You can add the url as a property to 'noti', then call that property with this.yourpropertyname
example:
noti.myurl = 'http://stackoverflow.com';
...
noti.onclick = function(){
window.location.href = this.myurl;
};
hope this helps.
For anyone, who needs to open a new browser window(tab), but does not want the parent window(tab) to be replaced and focused upon notification click, this code snippet will do the trick:
var notification = new window.Notification("Hello!", {
body: "Hello world!",
data: "https://www.google.com/"
});
notification.onclick = function(event) {
event.preventDefault(); //prevent the browser from focusing the Notification's tab, while it stays also open
var new_window = window.open('','_blank'); //open empty window(tab)
new_window.location = event.target.data; //set url of newly created window(tab) and focus
};

Mootools script will not work in internet explorer 7

I hope you can help,
I am relatively new to mootools (and brand new to here) and I have been working on a basic open close div. It can be seen here: http://jsfiddle.net/jessicajet/2jZz5/. It includes a clickable link script I found elsewhere.
<script>
window.addEvent('load', function() {
Element.Events.outerClick = {
base : 'click',
condition : function(event){
event.stopPropagation();
return false;
},
onAdd : function(fn){
this.getDocument().addEvent('click', fn);
},
onRemove : function(fn){
this.getDocument().removeEvent('click', fn);
}
};
(function() {
var opener = $('box2');
var boxtoopen = $('box');
var testmorph = $('test')
boxtoopen.set('morph', {
duration: 800,
});
boxtoopen.addEvent('outerClick', function(event) {
boxtoopen.morph(".openOff");
testmorph.morph(".openOff2");
});
opener.addEvent('click', function(e) {
e.stop();
boxtoopen.morph(".openOn");
testmorph.morph(".openOn2");
});
})();
var clix = new dwClickables({
elements: $('.box2'),
anchorToSpan: true
});
});
</script>
It doesn't seem to be working in ie7 although it seems consistant across other browsers?
Can anyone help me resolve this problem and give me some advice for future use?
Kind regards,
Jessica
Typos are often te worst bugs to find ;) and IE can be very stern about it.
http://jsfiddle.net/2jZz5/2/
I added a missing semicolon (;) and removed a unneeded comma (,)
Before:
var opener = $('box2');
var boxtoopen = $('box');
var testmorph = $('test')
boxtoopen.set('morph', {
duration: 800,
});
After:
var opener = $('box2');
var boxtoopen = $('box');
var testmorph = $('test');
boxtoopen.set('morph', {
duration: 800
});