what is the use of window.open('','_self').close(); in chrome extension - google-chrome-extension

When I click the extension icon, a popup is shown.
After that, when I try to click "URL restrictions", it will open a window, after that when I click the popup again, the popup is overlapping that url restriction window.
The above issue happens on Windows only, not on Linux.
So I have added window.open('','_self').close(); which apparently fixed the issue. But not exactly. Is it correct? I have referred this Link and Link2 but can not understand the meaning.
What is the purpose of window.open('','_self').close();?
EDIT: this is my popup.js
function click(e) {
var windowObj = window.open(site_exception_url, 'url_window', params);
windowObj.focus();
window.close();
window.open('','_self').close();
return false;
}

On Windows the popup isn't closed automatically after a new window is opened from a link within the popup.
Close it in the click handler manually, this won't hurt Linux but will help on Windows:
document.addEventListener("click", function(event) {
if (event.target.localName == "a") {
close();
}
});
The related questions linked in your question don't apply here as the first is for userscripts, not extensions, and the second isn't for popups shown by the browser when you click the toolbar button.

Related

How to cause a chrome extension to close only by clicking on the icon or a button

I am developing a chrome extension, in which I have used iframe, which I want to keep open even if we do some activity on the active web page itself or open a new tab or a new window. The extension should get closed only on clicking on the extension icon again or by clicking a close button, present on the extension itself. I am hinting on something like join pouch extension.
Other questions pertaining to this topic only caters to opening a window through extension which remains open or keeping the extension popup open just for debugging purposes, by inspecting the popup.
I know there is a way to do this, since I have seen some extensions as such, but am unable to find.
You can embed that iframe into the DOM structure of every single page you open. Unfortunately, Google doesn't provide any solution besides a default popup that disappears when the first click outside of it happens. The flipside is, you'll need to run one instance of your content script per page, which might mean there will be hundreds of them running (at least for me as I'm a compulsive new-tab-opener).
This is one of the ways, how you can approach this.
Step 1. As I've already said, the default action on icon click is opening a popup. You can disable that behaviour by including the following entry in your manifest.json:
"browser_action": {},
Step 2. The next thing would be creating a content script that runs on every page. In your manifest, it would look like this:
"content_scripts": [
{
"run_at": "document_end",
"matches": ["*://*/*"],
"js": ["path/to/your/content/script.js"]
}
],
Step 3.
Your content script should embed that iframe you mentioned into the currently open page (when the DOM fully loaded).
window.addEventListener('load', function load(event) {
var iframe = document.createElement('iframe');
/* some settings, these are mine */
iframe.style.width = "250px";
iframe.style.background = "#eee";
iframe.style.height = "100%";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "1000000000000000";
iframe.frameBorder = "none";
/* end of settings */
iframe.src =
chrome.runtime.getURL("path/to/contents/of/your/iframe.html");
document.body.appendChild(iframe);
});
Step 4.
You must make sure, people can access iframe.html. Add this line to your manifest file:
"web_accessible_resources": ["path/to/contents/of/your/iframe.html"],
(or just add that file to the list if it was already there.
Step 5.
Create a function in your content script that knows how to hide your iframe. Something like that:
function toggle_iframe() {
if (iframe.style.width == "0px"){
iframe.style.width="250px";
} else {
iframe.style.width="0px";
}
}
Now, the only thing left is to know when to call it.
Step 6.
Unfortunately, background script is the only place that can get information about extension icon being clicked. Add this snippet to your background script:
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, { action: "must_toggle_iframe" });
})
});
It sends a message, when the icon has been clicked.
Step 7.
The last part is to allow your content script to receive that message. Your content script needs a listener.
chrome.runtime.onMessage.addListener(function(msg, sender) {
if (msg.action == "must_toggle_iframe"){
toggle_iframe();
}
}
Of course, the solution is not ideal, but you could refine it. For example by remembering in the chrome.storage.local/chrome.storage.sync whether the iframe has been hidden.

Why am I getting the previous tabs url?

I am trying to get the url of the window that is opened by clicking the element with id 'wrpr_1431108056877h'. The new window opens but getTitle() still returns the title of the original tab. On the video provided by Browserstack I am able to verify that the current tab is indeed the one that I am trying to access.
browser
.click('#wrpr_1431108056877h')
.pause(5000)
.getTitle()
.then((url: any) => {
console.log(url);
})
.end()
.catch((err: any) => {
console.log(err.message);
done(Error('Could not move'));
});
browser.getTabIds();
should give you a list of all the window handles that webdriver knows about.
then you can use
browser.getCurrentTabId();
to figure out which window is currently in focus (Maybe this is what you said you are doing from the BrowserStack video?)
My guess is that the newly opened window isn't the currently focused window. Hence any commands executed (like getTitle()) will happen on the previous window.
You can switch the focused window to the newly opened window by calling
browser.switchTab(windowHandle)
Then you can call getTitle() and it should return the correct title.
See the web driver docs on Window here: http://webdriver.io/api/window/getTabIds.html
(scroll all the down on the left hand side to see the complete Window section)
for more info.
Please call
browser.navigate().refresh()
Before calling
browser.gettitle().

How to open a hyperlink in separate browser tab in Coded UI

I have three different Hyperlinks on a web page
Planning.
Solutions.
Contact Us.
I want to open them in separate browser tab one by one using codedUI.
i have written the above code to obtain the list of Hyperlink
HtmlControl Hyperlink = new HtmlControl(browser);
Hyperlink.SearchProperties.Add(HtmlControl.PropertyNames.ControlType,"Hyperlink");
UITestControlCollection controls = Hyperlink.FindMatchingControls();
foreach(UITestControl control in controls)
{
if (control is HtmlHyperlink)
{
HtmlHyperlink link = (HtmlHyperlink)control;
if(link.InnerText=="Planning"|| link.InnerText== "Solutions")
{
//separate Tab logic goes here
}
}
}
I need the help related to opening a hyperlink in new browser tab. Is it possible in CodedUI ?
By default if you click the mouse middle button (or click the scroll wheel), it opens a link in new tab. I would modify your code as below in this case,
if(link.InnerText=="Planning"|| link.InnerText== "Solutions")
{
//Open Link in New tab, by clicking middle button
Mouse.Click(link, MouseButtons.Middle);
}
You can do this a couple different ways. I would use #Prageeth-Saravan 's approach first to see if it works because it's easier and actually tests your UI. You could also:
Get the URL from the found link control
Send the "New tab" keyboard shortcut
Reinstantiate your browser window object to be sure it's pointing to the new tab
Navigate to that URL
The reason why I bolded step 3 is regardless of approach, if you intend to assert or interact with anything in a new tab you're going to have to remember that the CodedUI software will still be "Looking" at the old tab until you reinitialize it.

How find to whether my Chrome extension was called by shortcut?

I have a Chrome extension with a popup that can also be opened by a shortcut. When the popup gets opened, can I find out whether the user has used the shortcut or whether they have clicked on the extension icon?
The reason is that I'd like to hint users to use the shortcut, but I don't want to show that hint to users who already know and use the shortcut.
Popup and shortcut are defined like this in manifest.json:
"browser_action": {
"default_icon": "images/icon48.png",
"default_popup": "popup.html",
"default_title": "__MSG_tooltip__"
},
"commands": {
"_execute_browser_action": {
"suggested_key": {
"default": "Ctrl+Shift+Space"
}
}
},
chrome.browserAction.onClicked.addListener
Not available, because:
Fired when a browser action icon is clicked. This event will not fire
if the browser action has a popup.
We has popup.
chrome.commands.onCommand.addListener
Not available, because:
The '_execute_browser_action' and '_execute_page_action' commands are
reserved for the action of opening your extension's popups. They won't
normally generate events that you can handle.
May try inject press listener to some page and track pressed of keys (on each page).
var isPressed;
document.body.addEventListener("keydown", function (e) {
if (!(e.keyCode != 17) || !(e.keyCode != 16) || !(e.keyCode != 32)) return;
isPressed = true;
});
From popup in moment expand send message to content_scripts:
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {action: "isPressed"}, function (responce) {
if (responce) {
}
});
});
After message receiving, listener in content scripts send variable isPressed as response:
chrome.runtime.onMessage.addListener(function (message, sender, response) {
if (message.action == "isPressed") {
response(isPressed);
}
});
If variable is true, means called via keystrokes, else on click on icon.
can I find out whether the user has used the shortcut or whether they
have clicked on the extension icon?
There seems to be no clean direct way of detecting that.
Since I put some effort into trying to find a workaround, I would like to share what I have considered/tried and reasons why it doesn't work:
Attach the keyboard shortcut to some custom command, modify popup page and then open it programmatically.
Doesn't work because there is no way to open the popup programmatically, at least not in current stable version of Chrome (v50).
Create a custom command with the same shortcut as "_execute_browser_action" and use it to send a message to the popup.
Doesn't work because two commands cannot share the same shortcut.
Try to capture keyup in the popup page immediately after loading.
I tested this and it seemed to work at first, but it is definitely not reliable. If the user only presses the keyboard shortcut very briefly, the keyup event is fired before the popup page gets a chance to register a listener for it.
Capture keydown on pages using a content script and then send a message to the popup page to let it know that the keyboard shortcut was pressed (as suggested by UserName above).
This should work on most pages, but the content script won't be able to capture the keypress in address bar and on certain pages (chrome://, chrome-extension://).
Difficult to implement because you need to take into account the fact that users can customize the shortcut on chrome://extensions page. Finding the currently assigned shortcut programmatically to test against it in the content script is surprisingly difficult, because chrome.commands.getAll() provides localized key names (eg. "Ctrl+Shift+Space" in English, but "Ctrl+Shift+Mezera" in Czech) There are languages where even Ctrl and Shift don't stay in English.

Adding an option to the right click menu for a Chrome extension

Does anyone know if it's possible to add to the mouse right click menu in Chrome another option which would communicate with an extension?
I mean, after installing an extension, another option would appear in the mouse's right click menu which will send to a listener opened by the extension the data.
Here is the solution:
rightClickHandler = function(){
//Do your stuff over that selected context menu
};
chrome.contextMenus.create({
title: "Bitly Short Link",
contexts:["link","selection"], // ContextType
onclick: rightClickHandler // A callback function
});
In manifest.json, have this permission:
{ "permissions": ["...", "contextMenus"], }
Hope it helps!

Resources