Safari extension, open new tab with HTML page, pass parameters - javascript

In my extension I want to open a new tab when a toolbar button is clicked (works), display a static HTML page with JavaScript on the tab (works) and pass data (URL from the originating page) to the new tab (does not work). I tried:
Using query parameters like myTab.url = safari.extension.baseURI + 'page.html?' + params, but the target page does not seem to have a location assigned (location.search giving no result).
myTab.page.dispatchMessage("url", "someUrl"); after opening the tab, but the message never arrives in the new tab (I suspect, it's already "through", when the tab has opened).
Any suggestions?

I parsed document.URL in opened page for specific parameter and it worked for me. E.g.
function __onLoad()
{
var p = $.url(document.URL);
alert(p.param("url"));
}
And two possible reasons for missed message:
You did not add message event listener on your page
You called dispatchMessage before event listener was added
Check Safari development doc at https://developer.apple.com/library/archive/documentation/Tools/Conceptual/SafariExtensionGuide/MessagesandProxies/MessagesandProxies.html

Related

Opening new tab with python Selenium (via javascript) suddenly stopped working

The Situation
I have this code below, which was working perfectly many many times the way it is, then all of a sudden it stopped working when it gets to the step of opening a new tab via javascript.
url = 'https://website'
opt = Options()
opt.add_argument('--start-maximized')
opt.add_argument("disable-infobars")
opt.add_experimental_option("detach", True)
service = Service(r'C:\Users\chromedriver_new.exe')
driver = webdriver.Chrome(options= opt,service = service)
login(url) ###function that opens the url and passes user/keyword - up to this part it's working perfectly
img_url = "https://website/" + url[30:55] + "/img.jpg" ##source of image I want to download
#The problem starts here, I've printed the img_url and I can open it fine in my navigator, but when I run the code it just stops here and never opens the new tab
#I've already tried changing the javascript by passing "+img_url+" directly
#I've also tried already to open a blank new tab and even this is not working
driver.execute_script('window.open(arguments[0],"_blank");',img_url) ###open link in new tab
time.sleep(2)
driver.switch_to.window(driver.window_handles[1]) ##change focus to new tab
time.sleep(2)
img_url_full = driver.find_element(By.XPATH,"/html/body/img").get_attribute("src") ##it gets the full path to the image, which includes a valid token that enables me to access (if I would try to downlaod the img_url directly it wouldn't work)
time.sleep(2)
urllib.request.urlretrieve(img_url_full,name) ##download image
Extra Information
I don't know if that has something to do with it, but usually my browser would always stay open unless I closed it manually (there is no close/quit on the code), but around the same time that the new tab stopped to work the browser started to close automatically right after the step of login - to avoid that I then had to add the
opt.add_experimental_option("detach", True)
(which is working).
The Question
Why is this happening and how could i debug this?

Javascript to reload a new tab page

window.open("http://google.com", '_blank');
var childWindow = "http://google.com";
childWindow.location.href = "http://google.com";
I have an eventAddListener that loads http://google.com on a new tab with a button press, but right after it opens the new tab of google.com, I want it to REFRESH again. NOT my base page but the NEW tab page, by itself. The code I showed is just one of the examples out of 5 pages worth of google search which don't work.
UPDATE:
var win = window.open('google.com', 'New Window'); setTimeout(function () { var win = window.open('google.com', 'New Window'); },3000);
This is the best i could come up with. It opens new tab and "Reloads" the new tab rather than refresh it.
What I want is for example, you click on new tab, you paste a link then press enter, which EXECUTES the link. I basically want a javascript function which EXECUTES the link.
You can't do this.
In order to trigger a reload in the new tab/window you need to run JS in that tab/window.
The same origin policy prevents this.
If you had control over the new page then you could have an event listener running in it and post a message asking that listener to trigger a refresh.
Obviously you can't do that with Google's page.
This question, however, reads like an XY problem. If the goal is to display fresh (and not old, cached, out of date) information and the target page is not a third party one then you shouldn't be using JS to hack your way around caching. Instead set better caching rules on the target page in the first place.
I worked on something similar in the past few weeks and the code below worked for me.
index.html
<button onclick="openTab()">New Tab</button>
<script>
function openTab(){
//this opens a new tab while creating a variable name for that tab
var newTab = window.open("https://google.com","_blank");
//this refreshes that new tab
newTab.location.reload();
}
</script>
Just to prove that this works on the new tab I used the code
<script>
function openTab(){
//this opens a new tab while creating a variable name for that tab
var newTab = window.open("https://google.com","_blank");
//this will alert in the new tab
newTab.alert("New Tab");
//before the following reload code takes effect
//this refreshes that new tab
newTab.location.reload();
}
</script>
Hopefully that's what you are looking for.
From my understanding you want the new tab to refresh once opened with JavaScript instead of the current tab where you run the JavaScript code from.
That's not directly possible. The JavaScript code will only run for the tab it was executed in. The newly opened tab does not know that JavaScript code should be running. The current tab cannot pass over instructions for the new tab to execute.
However, you can select the newly opened tab manually first and then execute Javascript code to refresh the page. But that probably defeats the purpose of what you're trying to do.

window.open remove reference from parent

I have one page with list of reports and after clicking on report it redirects me to internal report page in new tab with:
window.open(reportIdUrl,reportId);
So when i am back on report list and i want to open same report i will use
window.open("",reportId);
if(redirect.location.href === "about:blank" || redirect.location.href !== '<internalreportpage>') {
redirect = window.open(reportUrl,reportId);
redirect.focus();
} else {
redirect.focus();
}
But when someone from new tab with internal report page navigates somehow to report list page (within this tab) and then tries to open internal report page it will open it in same tab as it is tab reference not content reference.
Does anybody know some way to drop reference when i access if condition?
Something like:
window.open("",reportId);
if(redirect.location.href === "about:blank" || redirect.location.href !== '<internalreportpage>') {
window.dropReference(reportId) //change_me
redirect = window.open(reportUrl,reportId);
redirect.focus();
} else {
redirect.focus();
}
So it will create new tab with new reportId reference?
Thanks
EXAMPLE
--reportlistpage
linkToReport1 (window.open(report1Url,1))
linkToReport2 (window.open(report2Url,2))
.
.
.
You click on linkToReport1 - 2 tabs are opened. One with reportlistpage and one with internal-report/report1.
You go back to parent tab and click to linkToReport1. Tab is opened with reference to "1" and will focus to it and no new tab is opened (this is ok).
You are on linkToReport1 and you redirect with some menu hyperlink to reportlistpage (within linkToReport1 tab). Url changed to /report-list
You click to linkToReport1. Nothing happen (this is not ok) because you are on the tab with reference to 1 (content and url changed), now you want to open a new tab with /internal-report/report1 url and store it as 1 with window references.
I figured it out. It is bit simple when you realize you can set or reset window.name. So there is nothing like references from parent.
Based on content you can do something following. In the page you want to keep track in tab,
at the beginning (in my case internalReport id):
var currentWindow = window.self;
currentWindow.name = reportId; //this is in case someone manually opened it without window.open(internalReportUrl, reportId)
then bind resetting of window.name on beforeunload event (e.g.):
var resetWindowName = function() {
var currentWindow = window.self;
currentWindow.name = ""
}
window.addEventListener('beforeunload', resetWindowName);
So when you redirect from internalreportpage somewhere, name is cleared and you can repeadetly call
window.open(internalReportUrl,reportId)
which will open new tab for you.

Force window.open() to create new tab in chrome

I use window.open to populate a new window with varying content. Mostly reports and stored HTML from automated processes.
I have noticed some very inconsistent behavior with Chrome with respect to window.open().
Some of my calls will create a new tab (preferred behavior) and some cause popups.
var w = window.open('','_new');
w.document.write(page_content);
page_content is just regular HTML from AJAX calls. Reports contain some information in the header like title, favicon, and some style sheets.
In IE9 the code does cause a new tab instead of a pop-up, while Chrome flatly refuses to show the content in question in a new tab. Since the content is sensitive business data I cannot post it here. I'll answer questions if I can.
I know some people will say this is behavior left up to the user, but this is an internal business platform. We don't have time to train all the users on how to manage popups, and we just need it to be in a new tab. Heck, even a new window would be preferable to the popup since you cannot dock a popup in Chrome. Not to mention none of the popup blocking code would affect it.
Appreciate any insight.
window.open must be called within a callback which is triggered by a user action (example onclick) for the page to open in a new tab instead of a window.
Example:
$("a.runReport").click(function(evt) {
// open a popup within the click handler
// this should open in a new tab
var popup = window.open("about:blank", "myPopup");
//do some ajax calls
$.get("/run/the/report", function(result) {
// now write to the popup
popup.document.write(result.page_content);
// or change the location
// popup.location = 'someOtherPage.html';
});
});
You can try this:
open a new tab please
<script>
function openWindow(){
var w = window.open("about:blank");
w.document.write("heheh new page opened");
}
</script>
Is very easy, in order to force Chrome to open in a new tab, use the onmouseup event
onmouseup="switchMenu(event);"
I have tried this and it worked fine in chrome. If opening a new tab is on a user action(such as a mouse click) this will work fine without any issues. But if the code is executed in another script block, you may need to enable pop-ups in chrome. Looks like this is to handle all the click-bait sites.
let newTab = window.open('', '_blank');
if (this.viewerTab == null) {
console.log("opening in new tab to work, pop-ups should be enabled.");
return;
}
................
newTab.location.href = viewerUrl;
window.open('page.html', '_newtab');
Specify the '_newtab'. This works in IE and FF, and should work in Chrome. But if the user has things configured to not open in new tab then not much you can do.

How to pass values to new tab opened by chrome.tabs.create?

I am new to writing extensions for Chrome. I am trying to write a simple extension that will open a new tab with the specified url, on a click of the extension icon and need to pass a value to it so that this value is filled in the input area (ex: input for search) of the specified url.
I am successful in opening the new tab with the given url on clicking the icon. I used background script to listen for the event on the icon and open a tab, the script is as follows:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': 'www.google.com'}, function(tab1) {
// Tab opened.
});
});
Now I am confused about what method will allow me to send some values to the new tab and use the value and perform some operation there like, if I pass "java api" I have to put this in the search area of the google page. I tried looking the Chrome extension docs but it is confusing as to what to use?
You should use chrome.tabs.executeScript() to run a content script in this tab:
chrome.tabs.create(..., function(tab1) {
chrome.tabs.executeScript(tab1.id, {file: ...});
});
This content script will then be able to do something with the tab contents. If it needs some data from your extension it will have to send a message.

Categories