Opening a new tab on Google Chrome Extension - javascript

This is my background.html file, It works fine when opening in current tab but I want it to open in new tab, what am I doing wrong?
<html>
<head>
<script>
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
var action_url = "javascript:location.href='http://www.reddit.com/submit?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title)";
chrome.tabs.create(tab.id, {url: action_url}, function(tab));
});
</script>
</head>
</html>

You should read the chrome.tabs.create documentation again. You are passing it invald parameters. You are also using location which is from the background.html document not the webpage document the code is expecting instead of the tab parameter passed to the chrome.browserAction.onClicked listener.
<html>
<head>
<script>
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
var action_url = "http://www.reddit.com/submit?url=" + encodeURIComponent(tab.href) + '&title=' + encodeURIComponent(tab.title);
chrome.tabs.create({ url: action_url });
});
</script>
</head>
</html>

You can try this
<html>
...
<body>
<script>
function createTab() {
chrome.tabs.create({url: "http://www.stackoverflow.com"});
}
</script>
Create a new tab
</body>
</html>

<html>
<head>
<script type="text/javascript">
window.master = ({
newtab: function(url, callback) {
callback = callback === true ? (function() { this.close(); }) : callback;
try {
chrome.tabs.create({
url: url
});
if(typeof callback === "function") { callback.call(this, url); }
} catch(e) {
/* Catch errors due to possible permission issues. */
}
},
link: function(event, close) {
event = event ? event : window.event;
event.preventDefault();
this.newtab(event.href, close);
},
close: function() { window.self.close(); }
});
</script>
</head>
<body>
<!-- Usage is simple:
HTML:
<a href="http://example.com/" onclick="master.link(event)" />
JavaScript:
master.newtab("http://example.com/", true);
-->
</body>
</html>
If you insist on using a popup and want it to close as soon as it is opened, then use what is above. Simply add the link string and a true boolean to the master.newtab function to have it open the new tab and then close the popup.
If you change your mind about closing the popup, you can replace the true boolean with a function to execute if the new tab was created without any errors. You can also use the master.link function for calling the master.newtab function from an anchor element.
The best thing about using Chrome Extensions is you never have to worry about support issues! :D

Related

Chrome Extension - Trigger not Work

i try create simple Chrome Extension, after click button in pop-up, i need send function setInput() to page, function change value and i need use trigger('keyup'), if i try use this function in Chrome Console - trigger work. But if i send this function after click in pop-up - trigger not work(
Chrome Extension - Trigger not Work
Console - Trigger Work
popup.html
<head>
<script src="popup.js"></script>
</head>
<body>
<div class="btn">Click</div>
</body>
popup.js
function sendMessage() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
}
function onWindowLoad() {
chrome.tabs.executeScript(null, { file: "PageReader.js" });
}
document.addEventListener("DOMContentLoaded", function() {
var btn = document.querySelector('.btn');
btn.addEventListener('click', function() {
sendMessage();
});
});
window.onload = onWindowLoad;
PageReader.js
- in file top i include Jquery
function setInput() {
var input = $('.text input');
input.val('1111').trigger('keyup');
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
setInput();
}
}
);
thanks all for help, i find answer, i delete jQuery, and create event "keyup"
Old:
var input = $('.text input');
input.val('1111').trigger('keyup');
New:
var evt = document.createEvent('KeyboardEvent');
evt.initEvent('keyup', true, true);
var input = document.querySelector('.text input');
input.value = '1111';
input.dispatchEvent(evt);
Please add debugger after btn.addEventListener('click', function() { too see what is going on. if this event handler is attached.
Second thing - you may want to wrap you initialisation code into setTimeout call with let's say 100ms of delay, to check if this page you are dealing with is not only working with some framework that generates this HTML and this is done after DOMContentLoaded. This means basically wrap everything inside
document.addEventListener("DOMContentLoaded", function() {
with setTimeout(function() {/*everything inside goes here*/}, 100)

Content script to update specific tab popup

Let's have an imaginary extension which takes everything after '/' from url, which is done in content script. Also updates badge and change text in popup.html, which different for every tab (different tab, diff. url)
contentscript.js:
var str = document.URL;
var n = str.lastIndexOf('/');
var result = str.substring(n + 1);
chrome.runtime.sendMessage({message: "result", url: result});
eventpage.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message == "result") {
chrome.browserAction.setBadgeText({tabId:sender.tab.id, "text" : "1"});
links = request.url;
}
popup.js:
$(function () {
var bg = chrome.extension.getBackgroundPage();
$('#total').text(bg.links);
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Plugin</title>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div id='total'>Nothing</div>
</body>
</html>
This works only on new loaded tabs, not when I click between them. For example, when I load first page "webpage.com/first" my popup's got 'first'. When I load second page(on different tab) "webpage.com/second" popup is 'second'. After that I click on the first page (on the first tab) and my popup is 'second' which I meant to be 'first'.
//badge in my project is counter, I wrote it here only for getting an idea
If you only need to get the tab url you can do it without content scripts just by using chrome.tabs.query in popup.js:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
$('#total').text(tabs[0].url.replace(/^.+?\/([^\/]*)$/, '$1'));
});
Otherwise use chrome.tabs.executeScript in popup.js:
chrome.tabs.executeScript({
code: "document.querySelector('p.something').textContent"
}, function(results) {
$('#something').text(results[0]);
});
Both methods require "activeTab" permission in manifest.json.

Disable link after child window is open, restore once child window is closed

My client has a link on their website which opens a customer service chat window in a popup. They are seeing users clicking the chat link multiple times, which opens multiple chat sessions, and it is throwing off their stats. I need to disable the link when the chat window is opened, and restore it when the chat window has been closed. I can't modify/access child window.
The original link looks like this:
<a class="initChat" onclick="window.open('https://chatlinkhere.com','chatwindow','width=612,height=380,scrollbars=0'); return false;">
I figured the best thing to do would be to store the window.open() as a variable in a function:
function openChat() {
child = window.open('http://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0,menubar=0');
}
and change the link HTML to
<a class="initChat" onclick="openChat();">
Note: Ideally, I'd like to detect the original onclick's value, and store it in a variable. Something like:
jQuery('.initChat').find().attr('onclick');
But I'm not sure how to store it and then call it later.
Next I need to run a check to see if the chat window is open or not:
timer = setInterval(checkChild, 500);
function checkChild() {
if (child.open) {
alert("opened");
jQuery(".initChat").removeAttr("onclick");
jQuery(".initChat").css("opacity", ".5");
clearInterval(timer);
}
if (child.closed) {
alert("closed");
jQuery(".initChat").attr('onclick', 'openChat(); checkChild();');
jQuery(".initChat").css("opacity", "1.0");
clearInterval(timer);
}
}
Note: the alerts are just there for testing.
And add the new function to the link
<a class="initChat" onclick="openChat(); checkChild();">
And once the chat window is closed, I need to restore the onclick attribute to the link (is there an easier way to do this?)
Fiddle demo is here -> http://jsfiddle.net/JkthJ/
When I check Chrome Console I'm getting error
Uncaught TypeError: Cannot read property 'open' of undefined
UPDATE
Whoever left me the answer in http://jsfiddle.net/JkthJ/2/ thank you very much it works! :)
i think you need is open pop up if already open then foucus on pop up or noyhing should happen
you can rewrite your function as
var winPop = false;
function OpenWindow(url){
if(winPop && !winPop.closed){ //checks to see if window is open
winPop.focus(); // or nothing
}
else{
winPop = window.open(url,"winPop");
}
}
just do it in a simple way. disable the mouse events on anchor link after child window open.
css
.disableEvents{
pointer-events: none;
}
js
var childWindow;
$('a').on('click',function(){
childWindow = window.open('_blank',"height:200","width:500");
$(this).addClass('disableEvents');
});
if (typeof childWindow.attachEvent != "undefined") {
childWindow.attachEvent("onunload", enableEvents);
} else if (typeof childWindow.addEventListener != "undefined") {
childWindow.addEventListener("unload", enableEvents, false);
}
enableEvents = function(){
$('a').removeClass('disableEvents');
};
update
your child window is plain html page. Do the changes in child window html code:
<html>
<head>
<script>
function myFunction()
{
window.opener.enableEvents(); //it calls enableEvents function
}
</script>
</head>
<body onunload="myFunction()">
<!--your content-->
</body>
</html>
This is what I got to finally work:
<a class="initChat" onclick="checkWin()"></a>
<script>
var myWindow;
function openWin() {
myWindow = window.open('https://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0');
}
function checkWin() {
if (!myWindow) {
openWin();
} else {
if (myWindow.closed) {
openWin();
} else {
alert('Chat is already opened.');
myWindow.focus();
}
}
}
</script>

Javascript not executing when right clicked into new tab

Here is my simple code
function goto() {
/* Some code to be executed */
if (a == "1")
location.href = "http://www.google.com";
else
location.href = "http://www.example.com";
}
And here is html
Hello
this works perfectly fine when i click normally but if i right click it and open in a new tab it doesn't execute.
try this:
Hello
function goto() {
/* Some code to be executed */
window.open("http://www.google.com");
}
if you want to open in new tab on mouse right click,
Hello
hit mouse right click and open in new tab
OR
u can try this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function goto() {
window.location = "http://www.google.com";
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('a')[0].addEventListener('contextmenu', function (ev) {
ev.stopPropagation();
ev.preventDefault();
goto();
});
document.getElementsByTagName('a')[0].addEventListener('click', function (ev) {
goto();
});
}, false)
</script>
</head>
<body>
Hello
</body>
</html>
Try something like this:
Hello
<script>
document.getElementById('myId').addEventListener('contextmenu', function(ev){
gotoFunc(ev);
});
function gotoFunc(ev){
//run this when right clicked over #myId element
}
</script>
do it like this:
function changeDest(elem) {
/* Some code to be executed */
if (a == "1")
elem.href = "http://www.google.com";
else
elem.href = "http://www.example.com";
}
Hello
you can instead use Hello
This should do the trick. i.e adding the url to the href of the anchor tag

HashChange events stop firing when an Angular ng-include exists on the page

I have the following HTML+Angular app shell that does everything I need it to do:
If the URL hash is empty when the page loads, it gets initialized to #/.
Whenever the URL hash changes, the view variable is updated.
This much works perfectly:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
<script>
function Router($scope) {
if (location.hash === "") location.hash = "#/";
$scope.view = createView(location);
window.addEventListener("hashchange", function (event) {
$scope.view = createView(event.newURL);
$scope.$apply();
});
}
function createView(url) {
var parser = document.createElement("a");
parser.href = url.toString();
var hash = parser.hash;
return (hash.replace("#/", "/views/") + "/index.html").replace("//", "/");
}
</script>
</head>
<body ng-controller="Router">
Navigation:
one
two
Partial: {{view}}
<!--<div ng-include="view"></div>-->
</body>
</html>
Then only problem is that as soon as I uncomment the div[ng-include], everything stops working. Specifically, the hashchange events stop firing. Am I doing something wrong or is this a bug? Any workarounds?

Categories